开发中有事须要一个功能是教师机经过广播发送给学生机实现通信,这时能够考试使用socket的udp广播功能来实现,代码以下:socket
using System;
using System.Text;
using UnityEngine;
using System.Net.Sockets;
using System.Net;
public class NewBehaviourScript : MonoBehaviour
{
private UdpClient UDPrecv;
private void Start()
{
UDPrecv = new UdpClient();
Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
socket.Bind(new IPEndPoint(IPAddress.Any, 9999));
UDPrecv.Client = socket;
UDPrecv.BeginReceive(ReceiveCallback, null);
}
private void Update()
{
Broad("这是一条广播信息");
}
public void Broad(string mes)
{
UdpClient UDPsend = new UdpClient(new IPEndPoint(IPAddress.Any, 0));
IPEndPoint endpoint = new IPEndPoint(IPAddress.Broadcast, 9999);
byte[] message = Encoding.UTF8.GetBytes(mes);
UDPsend.Send(message, message.Length, endpoint);
}
private void ReceiveCallback(IAsyncResult ar)
{
IPEndPoint endpoint = null;
byte[] recvBuf = UDPrecv.EndReceive(ar, ref endpoint);
string msg = Encoding.UTF8.GetString(recvBuf);
Debug.Log("收到"+ endpoint.Address+"的广播消息:"+ msg);//收到广播后打印一下,须要须要注意的是这个是子线程,须要UI等操做须要本身转到主线程
UDPrecv.BeginReceive(new AsyncCallback(ReceiveCallback), null);//收到信息后继续开始接受信息
}
}