其他分享
首页 > 其他分享> > Socket-UDP-Base

Socket-UDP-Base

作者:互联网

 

 

Server:

using System.Text;


Console.WriteLine("UDP Server Satrt...");
Socket udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress iPAddress = new IPAddress(new byte[] { 192, 168, 2, 103 });//IP
IPEndPoint endPoint = new IPEndPoint(iPAddress, 7788);//port

udpServer.Bind(endPoint);
var data = new byte[1024];
EndPoint ep = (EndPoint)new IPEndPoint(IPAddress.Any, 0);//IP范围
int len=udpServer.ReceiveFrom(data, ref ep);
Console.WriteLine($"accept:{Encoding.UTF8.GetString(data,0,len)}");
Console.ReadLine();

 

Client:

using System.Net;
using System.Net.Sockets;
using System.Text;

Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress iPAddress = new IPAddress(new byte[] { 192, 168, 2, 103 });//IP
IPEndPoint endPoint = new IPEndPoint(iPAddress, 7788);//port 

var msg = "Client call Server";
var sendBytes = Encoding.UTF8.GetBytes(msg);
Console.Write($"send:{msg}");
udpClient.SendTo(sendBytes, endPoint);
Console.WriteLine("\t send -OK");
Console.ReadLine();

 

标签:UDP,endPoint,Console,Socket,IPEndPoint,Base,new,IPAddress
来源: https://www.cnblogs.com/Zingu/p/16369384.html