UDP服务器通信
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
internal class Test
{
private static Socket socket;
private static Thread thread;
public static void Main()
{
socket=new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
socket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"),7788));
thread = new Thread(show){IsBackground = true};
thread.Start();
Console.ReadKey();
}
public static void show()
{
while (true)
{
EndPoint remoteEndpoint = new IPEndPoint(IPAddress.Any, 0);
Byte[] data = new byte[1024];
int len = socket.ReceiveFrom(data, ref remoteEndpoint);
string str = Encoding.UTF8.GetString(data, 0, len);
Console.WriteLine(str);
Console.WriteLine("地址;" + (remoteEndpoint as IPEndPoint).Address);
Console.WriteLine("端口:" + (remoteEndpoint as IPEndPoint).Port);
}
}
}
UDP客户端通信
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
internal class Test
{
public static void Main()
{
Socket socket=new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
while (true)
{
EndPoint point = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 7788);
string str = Console.ReadLine();
Byte[] data = Encoding.UTF8.GetBytes(str);
socket.SendTo(data, point);
}
Console.ReadKey();
}
}
2.使用封装的类来实现
//创建主机
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
internal class Test
{
public static void Main()
{
UdpClient udpclient=new UdpClient(new IPEndPoint(IPAddress.Parse("127.0.0.1"),7788));
//创建UDPclient
IPEndPoint point=new IPEndPoint(IPAddress.Any,0);
Byte[] data = udpclient.Receive(ref point);
//接受数据和对方主机信息
string str = Encoding.UTF8.GetString(data, 0, data.Length);
Console.WriteLine(str);
}
}
//创建客户端
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
internal class Test
{
public static void Main()
{
UdpClient client = new UdpClient();
string str = Console.ReadLine();
Byte[] data = Encoding.UTF8.GetBytes(str);
//client.Send(data, data.Length,new IPEndPoint(IPAddress.Parse("127.0.0.1"),7788));
client.Send(data, data.Length, "127.0.0.1", 7788);
Console.ReadLine();
}
}