1.udp-服务器端的实现
使用udp协议传输数据不需要建立连接
第一步创建Socket,第二步给服务器的Socket绑定ip和port,这个Socket就可以通过这个ip和port接收数据了。
第三步接收数据,在本例中通过新建线程的方式来接收数据,将线程设置为后台线程,这样在进程结束的时候,接收数据也不需要了。在ReceiveMessage的函数中实现了接收数据。ReceiveFrom的方法将数据存入data中,将数据来源的ip和port存入了一个EndPoint中。
class Program
{
private static Socket udpServer;
static void Main(string[] args)
{
//1.Socket creat
udpServer = new Socket
(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//2.Bind ip and port
udpServer.Bind(new IPEndPoint(IPAddress.Parse("192.168.1.103"),7788));
//3.receive data
new Thread(ReceiveMessage) {
IsBackground = true}.Start();
Console.ReadKey();
}
static void ReceiveMessage()
{
while (true)
{
EndPoint remoteEndPoint = ne

本文介绍了如何在C#中使用UDP协议实现消息的接收和发送。在服务器端,通过创建Socket并绑定IP和端口,利用后台线程的ReceiveFrom方法持续接收数据。客户端则只需指定目标IP和端口即可发送数据。
最低0.47元/天 解锁文章
2980

被折叠的 条评论
为什么被折叠?



