在Unity中使用UdpClient进行广播

本文章为笔记文章。
Unity中有Network相关的组件,极少使用.net中的网络函数。请在使用.net前仔细查阅Unity是否已存在相关功能,避免重复造车。以下为​要包含的库。
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using UnityEngine;
using UnityEngine.Networking;


UDP网络通讯分为广播消息和接受消息,由于这两种操作长期处在程序后方运行,故将其脱离主线程,使用多线程实现。所以在上面的库中包含了System.Threading。
为了实现扩展,将自定义类继承自NetworkManager。
public class NetworkMyManager : NetworkManager {
}


接下来定义所需的数据结构。
//UDP,使用UdpClient的基本对象
//messageReceive用于在“异步接收”操作中标识是否已接收消息。
//UDPrecv用于定义UdpClient对象。
//endpoint用于存储要进行广播的IP地址及端口
private bool messageReceive;
private UdpClient UDPrecv;
private IPEndPoint endpoint;


//UDP广播
//buf[]为要进行广播的消息
//broadThread 为广播线程
private byte[] buf;
private Thread broadThread;


//UDP接收
//recvBuf[] 为接收到的消息
//recvThread 为接收线程
private byte[] recvBuf;
private Thread recvThread;


在Start()事件中实现UdpClient的实例化、广播线程、接收线程的启动
void Start () {
UDPrecv = new UdpClient(new IPEndPoint(IPAddress.Any, 1111));
endpoint = new IPEndPoint(IPAddress.Any, 0);


broadThread = new Thread(new ThreadStart(BroadThread));
broadThread.IsBackground = true;
broadThread.Start();


recvThread = new Thread(new ThreadStart(RecvThread));
recvThread.IsBackground = true;
recvThread.Start ();
}


广播线程的实现
private void BroadThread()
{
UdpClient UDPsend = new UdpClient(new IPEndPoint(IPAddress.Any, 0));
IPEndPoint endpoint = new IPEndPoint(IPAddress.Broadcast, 1111);
while (true) {
UDPsend.Send (buf, buf.Length, endpoint);
Thread.Sleep (1000);
}
}


接收线程的实现(异步接收)
private void ReceiveCallback(IAsyncResult ar)
{
recvBuf = UDPrecv.EndReceive (ar, ref endpoint);
string msg = Encoding.Default.GetString(recvBuf);
messageReceive = true;
}
private void RecvThread()
{
messageReceive = true;
while (true) {
if (messageReceive) {
UDPrecv.BeginReceive (new AsyncCallback (ReceiveCallback), null);
messageReceive = false;
} else {
Thread.Sleep (100);
}
}
}

你可能感兴趣的:(在Unity中使用UdpClient进行广播)