UDP服务端
class Program
{
private static Socket udpServer;
static void Main(string[] args) {
udpServer = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
udpServer.Bind( new IPEndPoint( IPAddress.Parse("192.168.2.124"),7788 ) );
new Thread(ReceiveMessage){ IsBackground = true}.Start();
Console.ReadKey();
}
static void ReceiveMessage()
{
while (true)
{
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
byte[] data = new byte[1024];
int length = udpServer.ReceiveFrom(data, ref remoteEndPoint);
string message = Encoding.UTF8.GetString(data, 0, length);
Console.WriteLine("从ip:" + (remoteEndPoint as IPEndPoint).Address.ToString() + ":" + (remoteEndPoint as IPEndPoint).Port + "收到了数据:" + message);
}
}
}
客户端
class Program {
static void Main(string[] args) {
Socket udpClient = new Socket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp);
while (true)
{
EndPoint serverPoint = new IPEndPoint(IPAddress.Parse("192.168.2.124"), 7788);
string message = Console.ReadLine();
byte[] data = Encoding.UTF8.GetBytes(message);
udpClient.SendTo(data, serverPoint);
}
udpClient.Close();
Console.ReadKey();
}
}