Socket(套接字)变成UDP

1.

 

 

 

1.创建socket
2.绑定一步写到位

分步骤写:

3.接受数据:需要开启线程,线程开启的是一个方法:

服务器端建立完毕

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Net;
 5 using System.Net.Sockets;
 6 using System.Text;
 7 using System.Threading;
 8 using System.Threading.Tasks;
 9 
10 namespace SocketUdp服务器
11 {
12     class Program
13     {
14         public static Socket socketUdp;
15         static void Main(string[] args)
16         {
17             //1.创建Socket
18              socketUdp = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
19             //2.绑定本地Ip
20             IPAddress iPAddress = IPAddress.Parse("10.0.208.54");
21             EndPoint endPoint = new IPEndPoint(iPAddress, 7788);
22             socketUdp.Bind(endPoint);
23             //3.接收数据,需要开启线程
24             Thread thread = new Thread(AcceptMessage);
25             thread.Start();
26             Console.ReadKey();
27 
28         }
29         public static void AcceptMessage()
30         {
31             while (true)
32             {
33 
34             EndPoint endPoint = new IPEndPoint(IPAddress.Any,0);
35             byte[] data = new byte[1024];
36             int length=  socketUdp.ReceiveFrom(data,ref endPoint);
37             string mess=   Encoding.UTF8.GetString(data,0,length);
38             Console.WriteLine("客户端发来消息"+mess);
39             }
40         }
41     }
42 }

 


 

 建立客户端:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Net;
 5 using System.Net.Sockets;
 6 using System.Text;
 7 using System.Threading.Tasks;
 8 
 9 namespace 客户端Udp
10 {
11     class Program
12     {
13         static void Main(string[] args)
14         {
15             //1.建立Socket
16             Socket socketCline = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
17             //2.发送内容
18             while (true)
19             {
20 
21             string mess = Console.ReadLine();
22             byte[] data=  Encoding.UTF8.GetBytes(mess);
23             socketCline.SendTo(data,new IPEndPoint(IPAddress.Parse("10.0.208.54"),7788));
24             }
25 
26             Console.ReadKey();
27         }
28     }
29 }
View Code

 


 

 运行步骤:先运行服务器端,再运行客户端

 

posted @ 2018-10-08 17:13  白纸菇凉  阅读(568)  评论(0编辑  收藏  举报