C#Socket网络编程(三) UDP服务器端和客户端连接

 

Socket(套接字)编程(Udp)

基于Udp协议是无连接模式通讯,占用资源少,响应速度快,延时低。至于可靠性,可通过 应用层的控制来满足。(不可靠连接)     

(1).建立一个套接字(Socket)     

(2).绑定服务器端IP地址及端口号--服务器端     

(3).通过SendTo()方法向指定主机发送消息 (需提供主机IP地址及端口)     

(4).通过ReciveFrom()方法接收指定主机发送的消息 (需提供主机IP地址及端口)

TCP和UDP的区别
TCP协议和UDP协议连接过程的区别
1.基于连接与无连接;
2.对系统资源的要求(TCP较多,UDP少);
3.UDP程序结构较简单;
4.流模式与数据报模式 ;
5.TCP保证数据正确性,UDP可能丢包,TCP保证数据顺序,UDP不保证。

UDP服务器端:

复制代码
 1 using System;
 2 using System.Net;
 3 using System.Net.Sockets;
 4 using System.Text;
 5 
 6 namespace _29_UDP服务器端
 7 {
 8     internal class Program
 9     {
10         static void Main(string[] args)
11         {
12 
13             Socket udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
14 
15             IPAddress ipAddress = new IPAddress(new byte[] { 192, 168, 31, 17 });
16             // IP + Port
17             IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 7788);
18 
19             udpServer.Bind(ipEndPoint);
20             //任何人都可以发送消息
21             IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 0);
22             EndPoint ep = (EndPoint)ipep;
23             byte[] data = new byte[1024];
24             int length = udpServer.ReceiveFrom(data, ref ep);
25 
26             Console.WriteLine("接收到数据:" + Encoding.UTF8.GetString(data, 0, length));
27 
28             udpServer.Close();
29         }
30     }
31 }
复制代码

UDP客户端:

复制代码
 1 using System;
 2 using System.Net.Sockets;
 3 using System.Net;
 4 using System.Text;
 5 
 6 namespace UDP客户端
 7 {
 8     class Program
 9     {
10         static void Main(string[] args)
11         {
12             //(SocketType.Dgram)数据包形式发送
13             Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
14             IPAddress iPAddress = new IPAddress(new byte[] { 192, 168, 1, 184 });
15             IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, 6688);
16             //消息转码为byte
17             byte[] data = Encoding.UTF8.GetBytes("客户端上线了");
18             //强转iPEndPoint为EndPoint
19             EndPoint ep = (EndPoint)iPEndPoint;
20             //发送消息
21             udpClient.SendTo(data, ep);
22         }
23     }
24 }
复制代码

 

posted @   小羊Coyang  阅读(2183)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示