C# 简单实现udp
服务端:
UdpClient udpClient = new UdpClient(7777);//端口
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
udpClient.Connect(RemoteIpEndPoint.Address.ToString(), Convert.ToInt32(RemoteIpEndPoint.Port));
Byte[] sendBytes = Encoding.ASCII.GetBytes("hello World! i am a server");
udpClient.Send(sendBytes, sendBytes.Length);
// udpClient.Close();
}
客户端:
UdpClient udpClient = new UdpClient(8888);
string ip = Dns.GetHostName().ToString();
udpClient.Connect(IPAddress.Parse("127.0.0.1"), 7777);
// Sends a message to the host to which you have connected.
Byte[] sendBytes = Encoding.ASCII.GetBytes("hello world! i am a client");
udpClient.Send(sendBytes, sendBytes.Length);
//IPEndPoint object will allow us to read datagrams sent from any source.
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
// Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
udpClient.Close();
浙公网安备 33010602011771号