UDP是无连接不安全的通信,但效率高,通常用在视频或语音通话等方面,要求高效率的传输,代码如下:
代码运行平台 Visual Studio 2019
服务端代码:
/*******
*
* UDP通讯:服务器端
* 和TCP不一样的地方:
* 1、不需要Listen()和Accept()了
* 2、UDP中用的是_SocketServer.ReceiveFrom(),而不是_SocketServer.Receive()
*
* *******/
using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace SocketServer_UDP
{
class Server
{
private Socket _SocketServer; //套接字
private bool _IsListenConnection = true; //是否在监听(目的是方便退出)
private IPEndPoint endPoint;
public Server()
{
//定义网络终节点(封装IP与端口)
endPoint = new IPEndPoint(IPAddress.Parse("192.168.1.8"), 8080);
//实例化套接字(监听)
_SocketServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//服务器端绑定地址
_SocketServer.Bind(endPoint);
Console.WriteLine("服务端已启动...");
Thread thSend = new Thread(SendMsg);
thSend.Start();
//这里必须另起一个线程,因为接收收时线程是卡着等待着的
Thread thReceive = new Thread(ReceiveMsg);
thReceive.Start();
}
/// <summary>
/// 接受客户端消息
/// </summary>
private void ReceiveMsg()
{
EndPoint ep = new IPEndPoint(IPAddress.Any,0); //Any代表任何客户端,0代表任何端口
while (true)
{
//准备一个“数据缓存”
byte[] msgArray = new byte[1024 * 1024]; //一个1M的空间
//接收客户端发来的消息,返回数据的真实长度
int trueClientMsgLength = _SocketServer.ReceiveFrom(msgArray, ref ep); //这里和TCP连接不一样了,用的是ReceiveForm()而不是Receive()????
//byte字节数组转string
string strMsg = Encoding.UTF8.GetString(msgArray, 0, trueClientMsgLength);
Console.WriteLine("客户端发来的数据: " + strMsg);
}
}
/// <summary>
/// 向指定客户端发送消息
/// </summary>
private void SendMsg()
{
//EndPoint ep = (EndPoint)endPoint;
while (true)
{
EndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.1.8"), 8081);
string snedMsg = Console.ReadLine(); //输入要发送的内容
byte[] byteMsg = Encoding.UTF8.GetBytes(snedMsg);
_SocketServer.SendTo(byteMsg, ep);
}
}
static void Main(string[] args)
{
Server server = new Server();
}
}
}
客户端代码:
/************
*
* UDP端通信:客户端
* 和TCP不一致的地方:
* 1、UDP发送用的是SendTo(),而TCP用的是Send()
*
* ************/
using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace SocketClient_UDP
{
class Client
{
private Socket _SocketClient; //客户端通讯套接字
private IPEndPoint serverEndPoint; //连接到的服务器IP与端口信息
public Client()
{
//(服务器端)通讯地址与端口号
serverEndPoint = new IPEndPoint(IPAddress.Parse("192.168.1.8"), 8081);
//建立客户端的Socket
_SocketClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//绑定
_SocketClient.Bind(serverEndPoint);
//另起一个发送线程
Thread thSendMsg = new Thread(SendMsg);
thSendMsg.Start();
//这里必须另起一个线程,接收时线程是卡着等待消息接收的
Thread thReceive = new Thread(ReceiveMsg);
thReceive.Start();
}
/// <summary>
/// 向服务端发送消息
/// </summary>
private void SendMsg()
{
try
{
EndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.1.8"),8080);
while (true)
{
//输入信息
string strMsg = Console.ReadLine();
//string转化为字节数组
byte[] byteArray = Encoding.UTF8.GetBytes(strMsg);
//发送数据
_SocketClient.SendTo(byteArray, ep); //这里和TCP不一致,TCP用的是Send()
Console.WriteLine("我: " + strMsg);
}
}
catch (Exception)
{
//关闭前端和后端连接
_SocketClient.Shutdown(SocketShutdown.Both);
//清理连接的资源
_SocketClient.Close();
}
}
/// <summary>
/// 接收服务端发送的消息
/// </summary>
private void ReceiveMsg()
{
try
{
EndPoint ep = (EndPoint)new IPEndPoint(IPAddress.Any, 0);
while (true)
{
byte[] bytes = new byte[1024 * 1024]; //定义一个1M的数据缓存空间
int trueClientMsgLength = _SocketClient.ReceiveFrom(bytes, ref ep); //真正接收到的数据长度
string strMsg= Encoding.UTF8.GetString(bytes, 0, trueClientMsgLength);
Console.WriteLine("服务端: " + strMsg);
}
}
catch (Exception)
{
throw;
}
}
static void Main(string[] args)
{
Client obj = new Client();
}
}
}
大家修改各自的IP地址后,此代码即可运行
运行结果如下:
下一节进行TCP通信的讲解.......