基于UDP
发送
// 本机ip和端口
var localIp = new IPEndPoint(IPAddress.Parse(ip), port);
var udpSocket = new Socket(serverIp.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
udpSocket.Bind(localIp);
public void Send(string ip, int port, byte[] buffer)
{
var remote = new IPEndPoint(IPAddress.Parse(ip), port);
udpSocket.SendTo(buffer, remote);
}
数据必须一次发送,不能分段发送,不然顺序会混乱,数据大小也要注意,因为接收时只能接收一次,多出的数据就会接收不到了
接收
// 本机ip和端口
var localIp = new IPEndPoint(IPAddress.Parse(ip), port);
var udpSocket = new Socket(serverIp.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
udpSocket.Bind(localIp);
var buffer = new byte[65536];
EndPoint sendIp = new IPEndPoint(IPAddress.Any, port);
var length = udpSocket.ReceiveFrom(buffer, Constants.UDP_BUFFER_SIZE,
SocketFlags.None, ref sendIp);
TCP
发送
var remoteIp = new IPEndPoint(IPAddress.Parse(ip), port);
var socket = new Socket(clientIp.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(remoteIp);
var buffer = new byte[8];
socket.Send(buffer);
private void Send(byte[] buffer, int length)
{
var index = 0;
while (index < length)
{
var size = socket.Send(buffer, index, length - index, SocketFlags.None);
index += size;
}
}
请注意,发送数据可以分多次,因为是保持顺序的,不会乱的,接收端也可以分多次接收,但是,不能保证一次发送全部数据,最好封装一个方法,保证数据全部发送了
接收
第一步接收每一个连接
var localIp = new IPEndPoint(IPAddress.Parse(ip), port);
var tcpSocket = new Socket(serverIp.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
tcpSocket.Bind(localIp);
tcpSocket.Listen(10);
while (true)
{
var client = tcpSocket.Accept();
}
第二步,从每一个连接中接收数据
var buffer = new byte[8];
client.Receive(buffer);
private byte[] Receive(int length)
{
var buffer = new byte[length];
var index = 0;
while (index < length)
{
var size = client.Receive(buffer, index,
length - index, SocketFlags.None);
index += size;
}
return buffer;
}
接收数据也会出现一次性接收不完,要分几次才能接收一段数据,最好是保持一问一答的方式发送和接收数据,保证数据的完整,不会出现丢包的问题
转载请保留原文链接: https://zodream.cn/blog/id/236.html