UDP发送和接收

时间:2024-09-20 11:33:44

发送函数

public bool udpSend(string ip, int port, byte[] data)
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress ipaddress = IPAddress.Parse(ip);
IPEndPoint ipendpoint = new IPEndPoint(ipaddress, port);
socket.SendTo(data, ipendpoint);
socket.Close();
return true;
}

接收

int port = ;
UdpClient udp_client = new UdpClient(port);
IPEndPoint ip_endpoint = new IPEndPoint(IPAddress.Any, port);
while (true)
{
byte[] data = udp_client.Receive(ref ip_endpoint);
}