一、介绍

        UDP 是User Datagram Protocol的简称,是一种传输层的协议,传输数据之前不需要建立连接,当它想发送数据时就直接扔到网络上。如果这个时候接收端正好在线并且网络通畅数据就接收到了。如果接收端不在线或者由于网络阻塞数据就丢失了。UDP传送数据的速度仅仅是受应用程序生成数据的速度、计算机的能力和传输带宽的限制。所以UDP的特点就是传输速度快,有丢包的风险,一般应用在需要高速传输且对数据安全性不那么高的程序上(比如:网络电话,视频聊天等)

 

二、服务端

using UnityEngine;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System;
using System.Collections;

namespace Mx.Net
{
/// <summary>UDP通信服务器</summary>
public class UdpServer : MonoBehaviour
{
private Socket m_Socket;
private EndPoint m_EndPoint;
private IPEndPoint m_IpEnd;
private byte[] m_RecvData = new byte[1024];
private byte[] m_SendData = new byte[1024];
private Thread m_Thread;
private Queue m_MsgQueue;
public Action<byte[]> onReceiveEvent = null;

private void Awake()
{
m_MsgQueue = new Queue();
}

private void OnDestroy()
{
Close();
}

private void Update()
{
//由于我们接受数据是在多线程上,所以接受到的数据我们需要返回到主线程使用
if (m_MsgQueue.Count != 0)
{
OnReceiveEvent((byte[])m_MsgQueue.Dequeue());
}
}

/// <summary>开启UPD服务器</summary>
public void OpenServer(int port)
{
m_IpEnd = new IPEndPoint(IPAddress.Any, port);
m_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
m_Socket.Bind(m_IpEnd);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
m_EndPoint = (EndPoint)sender;
m_Thread = new Thread(new ThreadStart(SocketReceive));
m_Thread.Start();
}

/// <summary>发送消息</summary>
public void SendMsg(string msg)
{
if (m_Socket == null||string.IsNullOrEmpty(msg)) return;

m_SendData = new byte[1024];
m_SendData = Encoding.ASCII.GetBytes(msg);
m_Socket.SendTo(m_SendData, m_SendData.Length, SocketFlags.None, m_EndPoint);
}

/// <summary>发送Bytes数据</summary>
public void SendBytes(byte[] data)
{
if (m_Socket == null|| data==null) return;

m_Socket.SendTo(data, data.Length, SocketFlags.None, m_EndPoint);
}

/// <summary>接收消息事件</summary>
private void OnReceiveEvent(byte[] data)
{
if (onReceiveEvent != null) onReceiveEvent(data);

string recvStr = Encoding.ASCII.GetString(data);
Debug.Log(GetType() + "/Receive()/接收到的消息:" + recvStr);
}

/// <summary>接收消息</summary>
private void SocketReceive()
{
while (true)
{
m_RecvData = new byte[1024];
int length = m_Socket.ReceiveFrom(m_RecvData, ref m_EndPoint);
byte[] data = new byte[length];
Array.Copy(m_RecvData, data, length);
m_MsgQueue.Enqueue(data);
}
}

/// <summary>关闭连接</summary>
private void Close()
{
if (m_Thread != null)
{
m_Thread.Interrupt();
m_Thread.Abort();
}

if (m_Socket != null) m_Socket.Close();
}

}
}

三、客户端

using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;

namespace Mx.Net
{
/// <summary>UDP通信客户端</summary>
public class UdpClient : MonoBehaviour
{
private Socket m_Socket;
private EndPoint m_EndPoint;
private IPEndPoint m_IpEnd;
private byte[] m_RecvData = new byte[1024];
private byte[] m_SendData = new byte[1024];
private Thread m_Thread;
private Queue m_MsgQueue;
public Action<byte[]> onReceiveEvent = null;

private void Awake()
{
m_MsgQueue = new Queue();
}

private void OnDestroy()
{
Close();
}

private void Update()
{
if (m_MsgQueue.Count != 0)
{
OnReceiveEvent((byte[])m_MsgQueue.Dequeue());
}
}

/// <summary>开启客户端</summary>
public void OpenClient(int port)
{
m_IpEnd = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);
m_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
m_EndPoint = (EndPoint)sender;

m_Thread = new Thread(new ThreadStart(SocketReceive));
m_Thread.Start();
}

/// <summary>发送消息</summary>
public void SendMsg(string msg)
{
if (m_Socket == null) return;

m_SendData = new byte[1024];
m_SendData = Encoding.UTF8.GetBytes(msg);
m_Socket.SendTo(m_SendData, m_SendData.Length, SocketFlags.None, m_IpEnd);
}

/// <summary>发送Bytes数据</summary>
public void SendBytes(byte[] data)
{
if (m_Socket == null) return;

m_Socket.SendTo(data, data.Length, SocketFlags.None, m_IpEnd);
}

/// <summary>接收消息</summary>
private void SocketReceive()
{
while (true)
{
m_RecvData = new byte[1024];
int length = m_Socket.ReceiveFrom(m_RecvData, ref m_EndPoint);
byte[] data = new byte[length];
Array.Copy(m_RecvData, data, length);
m_MsgQueue.Enqueue(data);
}
}

/// <summary>接收消息事件</summary>
private void OnReceiveEvent(byte[] data)
{
if (onReceiveEvent != null) onReceiveEvent(data);

string recvStr = Encoding.ASCII.GetString(data);
Debug.Log(GetType() + "/OnReceiveEvent()/接收到的消息:" + recvStr);
}

/// <summary>关闭客户端</summary>
private void Close()
{
if (m_Thread != null)
{
m_Thread.Interrupt();
m_Thread.Abort();
}

if (m_Socket != null) m_Socket.Close();
}
}
}

 

四、聊天室案例

--------------------Todo 稍后更新--------------------

 

Unity QQ交流群:299412191 欢迎对Unity感兴趣的同学加入.