C# socket如何做到命令收发对应
时间: 2023-11-01 11:22:17 浏览: 191
在C#中,可以使用Socket类来实现命令的收发对应。具体的实现方法如下:
1. 定义一个协议,规定命令的格式,包括命令名称和命令参数。
2. 在客户端和服务器端分别创建Socket对象,并连接到对方。
3. 在客户端中,将命令以指定的格式发送到服务器端;在服务器端中,接收到命令后,解析命令,并根据命令名称执行相应的操作。
4. 在客户端和服务器端中都需要使用异步方式来进行收发操作,以避免阻塞程序的运行。
示例代码如下:
客户端:
```
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class Client
{
private Socket clientSocket;
private byte[] buffer = new byte[1024];
public Client()
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
public void Connect(string ip, int port)
{
IPAddress ipAddress = IPAddress.Parse(ip);
IPEndPoint ipEndpoint = new IPEndPoint(ipAddress, port);
clientSocket.BeginConnect(ipEndpoint, new AsyncCallback(ConnectCallback), null);
}
private void ConnectCallback(IAsyncResult ar)
{
clientSocket.EndConnect(ar);
Console.WriteLine("Connected to server");
// 发送命令
SendCommand("CMD1 param1 param2");
}
private void SendCommand(string command)
{
byte[] cmdBytes = Encoding.ASCII.GetBytes(command);
clientSocket.BeginSend(cmdBytes, 0, cmdBytes.Length, SocketFlags.None, new AsyncCallback(SendCallback), null);
}
private void SendCallback(IAsyncResult ar)
{
int bytesSent = clientSocket.EndSend(ar);
Console.WriteLine("Sent {0} bytes to server", bytesSent);
// 接收响应
clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
}
private void ReceiveCallback(IAsyncResult ar)
{
int bytesRead = clientSocket.EndReceive(ar);
if (bytesRead > 0)
{
string response = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received response: {0}", response);
}
}
}
```
服务器端:
```
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class Server
{
private Socket serverSocket;
private byte[] buffer = new byte[1024];
public Server()
{
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
public void Start(int port)
{
IPEndPoint ipEndpoint = new IPEndPoint(IPAddress.Any, port);
serverSocket.Bind(ipEndpoint);
serverSocket.Listen(10);
Console.WriteLine("Server started");
serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}
private void AcceptCallback(IAsyncResult ar)
{
Socket clientSocket = serverSocket.EndAccept(ar);
Console.WriteLine("Client connected");
// 接收命令
clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), clientSocket);
}
private void ReceiveCallback(IAsyncResult ar)
{
Socket clientSocket = (Socket)ar.AsyncState;
int bytesRead = clientSocket.EndReceive(ar);
if (bytesRead > 0)
{
string command = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received command: {0}", command);
// 解析命令并执行操作
string[] parts = command.Split(' ');
string cmdName = parts[0];
string[] cmdArgs = new string[parts.Length - 1];
Array.Copy(parts, 1, cmdArgs, 0, cmdArgs.Length);
ExecuteCommand(cmdName, cmdArgs);
// 发送响应
byte[] responseBytes = Encoding.ASCII.GetBytes("OK");
clientSocket.BeginSend(responseBytes, 0, responseBytes.Length, SocketFlags.None, new AsyncCallback(SendCallback), clientSocket);
}
}
private void SendCallback(IAsyncResult ar)
{
Socket clientSocket = (Socket)ar.AsyncState;
int bytesSent = clientSocket.EndSend(ar);
Console.WriteLine("Sent {0} bytes to client", bytesSent);
// 继续接收命令
clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), clientSocket);
}
private void ExecuteCommand(string cmdName, string[] cmdArgs)
{
// 根据命令名称执行相应的操作
}
}
```
请注意,以上代码仅为示例,实际应用中还需要考虑许多其他因素,如错误处理、安全性等。
阅读全文