可分为两种:用C#本身的Socket或UdpClient;
1. udp通讯需指定两台机器的通讯IP和端口,即udp包发出机器的IP/Port和收到该包的IP/Port:
this.localIp = IPAddress.Parse(localIp);
this.remoteIp = IPAddress.Parse(remoteIp);
this.remotePort = remotePort;
this.localPort = localPort;
用socket时,需用Bind方法绑定本地IP和端口,即发出包的IP/Port:
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Bind(new IPEndPoint(this.localIp, this.localPort));
用UdpClient时,该绑定发出的socket方式已经写在UdpClient本身类中,构造时把本地IP和port传为参数:
udpClient = new UdpClient(new IPEndPoint(this.localIp, this.localPort));
2. 发送数据:
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.SetBuffer(data, 0, data.Length);
args.RemoteEndPoint = new IPEndPoint(IPAddress.Parse(this.remoteIp.ToString()), this.remotePort);
args.Completed += OnFireSendCompleted;
socket.SendToAsync(args);
或
IPEndPoint remoteIpEP = new IPEndPoint(this.remoteIp, this.remotePort);
udpClient.SendAsync(sendData, sendData.Length, remoteIpEP);
即可将数据发送到另一台指定机器IP/Port
c#有IPEndPoint类可用来指定IP/Port
3. 接收数据:
3.1 均可实现异步接收包操作:
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
var buff = new Byte[1024 * 100];
args.SetBuffer(buff, 0, buff.Length);
args.RemoteEndPoint = new DnsEndPoint(this.remoteIp.ToString(), this.remotePort);
args.Completed += (sender, e) =>
{
OnDataReceived(sender, e.Buffer);
};
socket.ReceiveAsync(args);
或
udpClient.ReceiveAsync();
3.2 接收数据后,当需要只响应特定IP/Port发来的数据时:
args.RemoteEndPoint = new DnsEndPoint(this.remoteIp.ToString(), this.remotePort);
或
IPEndPoint remoteEP = new IPEndPoint(this.remoteIp, this.remotePort);
UdpReceiveResult udpReceiveResult = await udpClient.ReceiveAsync();
if (udpReceiveResult.RemoteEndPoint.Equals(remoteEP))
{