一、UDP通信原理
UDP协议使用无连接的套接字,因此不需要再网络设备之间发送连接信息,但是必须用Bind方法绑定到一个本地地址/端口上。
①建立套接字
②绑定IP地址和端口作为服务器端
③直接使用SendTo/ReceiveFrom来执行操作
注意:同步Socket(UDP)通信存在缺点:只能单向接收或者发送数据
二、编写对应的控制台应用程序的服务器端与客户端脚本
<1>服务器端(信息发送端)脚本如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Test_Socket_UDP
{
class UDPSending
{
static void Main(string[] args)
{
UDPSending obj = new UDPSending();
Console.WriteLine("---发送端---");
obj.SocketUDPSending();
}
public void SocketUDPSending()
{
//定义发送字节区
byte[] byteArray = new byte[100];
//定义网络地址
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1000);
Socket socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
EndPoint ep = (EndPoint)iep;
//发送数据
Console.WriteLine("请输入发送的数据");
while (true)
{
string strMsg = Console.ReadLine();
//字节转换
byteArray = Encoding.Default.GetBytes(strMsg);
socketClient.SendTo(byteArray, ep);
if (strMsg == "exit")
{
break;
}
}
socketClient.Shutdown(SocketShutdown.Both);
socketClient.Close();
}
}//Class_end
}
<2>客户端端(信息接收端)脚本如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Test_Socket_UDPAccept
{
class UDPAccept
{
static void Main(string[] args)
{
UDPAccept obj = new UDPAccept();
Console.WriteLine("---接收端---");
obj.SocketUDPAccept();
}
//接收端
private void SocketUDPAccept()
{
//定义接收的数据区
byte[] byteArray = new byte[100];
//定义网络地址
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"),1000);
Socket socketServer = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
socketServer.Bind(iep);//地址绑定服务器端
EndPoint ep = (EndPoint)iep;
//接受数据
while (true)
{
int intReceiveLength = socketServer.ReceiveFrom(byteArray,ref ep);
string strReceiveStr = Encoding.Default.GetString(byteArray,0,intReceiveLength);
Console.WriteLine(strReceiveStr);
}
}
}//class_end
}
三、运行程序 ,测试如下
注:本内容来自《Unity3D/2D游戏开发从0到1》28章