开启一个线程做网络连接,和接收数据, 用event进行广播
using UnityEngine; using System.Collections; using System.Threading; //using System.Threading.Tasks; using System; using System.Net; using System.Net.Sockets; using System.Collections.Generic; using System.Linq; public class Alpha { public string v; public List<string> bytelist = new List<string>(); public static event Action<String> handler; public void Beta() { GameNet gamenet = new GameNet(); gamenet.start(); gamenet.send("1"); while(true){ try{ v = gamenet.conrecv(); bytelist.Add(v); gamenet.send ("1"); } catch(SocketException e){ v = "socket closed"; break; } if(handler != null){ handler(bytelist[0]); } bytelist.Clear(); } } }; public class thread : MonoBehaviour { Alpha oAlpha = new Alpha(); Thread oThread; void Start () { oThread = new Thread(new ThreadStart(oAlpha.Beta)); oThread.Start(); Alpha.handler += (s) => print ("client handler"); } void Update () { } void OnDestory(){ oThread.Abort(); } }
时间: 2024-10-28 17:45:06