Unity-使用UDP连接到服务器

时间:2018-06-29 06:49:40

标签: unity3d networking

我正在一个由客户端实现服务器逻辑的项目中。我无权访问服务器。从客户端,将几个数据发送到服务器,服务器在该服务器上应用计算并将结果返回给客户端。如何通过Unity客户端建立UDP通信?

1 个答案:

答案 0 :(得分:0)

我想知道您是否正在尝试从另一个线程调用Unity API。

也许有帮助。

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

public class UDPRT: ScriptableObject {
 static public string ReceivedMsg; // INPUT DATA
 static private UdpClient udpc;
 static IPEndPoint IP;
 static private object obj;
 static private AsyncCallback AC;
 static byte[] DATA;

 public static UDPRT CreateInstance(int Port) // RECEVE UDP
  {
   IP = new IPEndPoint(IPAddress.Any, Port);
   udpc = new UdpClient(Port);
   AC = new AsyncCallback(ReceiveIt);
   StartUdpReceive();
   return ScriptableObject.CreateInstance < UDPRT > ();
  }

 public static UDPRT CreateInstance(int Port, string Host, string msg) // SEND UDP
  {
   udpc = new UdpClient(Host, Port);
   AC = new AsyncCallback(SendIt);
   byte[] data = Encoding.UTF8.GetBytes(msg);
   udpc.BeginSend(data, data.Length, AC, obj);
   return ScriptableObject.CreateInstance < UDPRT > ();
  }

 static void ReceiveIt(IAsyncResult result) {
  DATA = (udpc.EndReceive(result, ref IP));
  Debug.Log(Encoding.UTF8.GetString(DATA));
  ReceivedMsg = Encoding.UTF8.GetString(DATA);
  StartUdpReceive();
 }

 static void SendIt(IAsyncResult result) {
  udpc.EndSend(result);
 }


 static void StartUdpReceive() {
  udpc.BeginReceive(AC, obj);
 }
}