我正在尝试使tcp服务器统一工作,而且还可以。我的系统的目的是从另一个程序中读取数据,该程序向我发送字节并为我绘制该数据的图片。主要问题是,当我运行它时,它会工作一段时间(随机时间),然后整个单位冻结,我需要从任务管理器中删除它。
void Start()
{
Display1 = gameObject.GetComponent<Renderer>();
mymat = GetComponent<Renderer>().material;
packetReady = false;
tcpListenerThread = new Thread(new ThreadStart(ListenForIncommingRequests));
tcpListenerThread.IsBackground = true;
tcpListenerThread.Start();
bytes = new byte[1024];
tex = new Texture2D(800, 1280, TextureFormat.RGB24, false);
firstTime = true;
ArrayInit(3072060);
packetLength = 3072060;
myThread = new Thread(Draw);
myThread.Start();
}
void Draw()
{
if (Loader == null)
{
return;
}
else if (packetReady)
{
tex.LoadRawTextureData(Loader);
tex.Apply();
mymat.SetTexture("_EmissionMap", tex);
Display1.material.mainTexture = tex;
packetReady = false;
}
}
void Update()
{
Draw();
}
private void ListenForIncommingRequests()
{
try
{
tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 35800);
tcpListener.Start();
while (true)
{
if (!tcpListener.Pending())
{
Thread.Sleep(100);
}
Thread.Sleep(10);
using (connectedTcpClient = tcpListener.AcceptTcpClient())
{
using (NetworkStream stream = connectedTcpClient.GetStream())
{
int length;
while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
{
if (bytes == null)
{
return;
}
else
{
ParseData(bytes);
}
}
}
}
}
}
catch (SocketException socketException)
{
Debug.Log("SocketException " + socketException.ToString());
}
finally
{
tcpListener.Stop();
}
}
我不知道是什么原因造成的,我试图解决该问题,但似乎没有任何效果。有什么建议么?