C# Can';t连接插座超过X次
我正在尝试用Unity3D编写一个程序,可以从Python应用程序接收和可视化数据:C# Can';t连接插座超过X次,c#,python,sockets,unity3d,tcp,C#,Python,Sockets,Unity3d,Tcp,我正在尝试用Unity3D编写一个程序,可以从Python应用程序接收和可视化数据: using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Net; using System.Net.Sockets; using System.Linq; using System; public class Visualizer : MonoBehaviour { Tc
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net;
using System.Net.Sockets;
using System.Linq;
using System;
public class Visualizer : MonoBehaviour {
TcpListener listener;
private Socket client = null;
private int i = 0;
const int byteCount = 1000;
private const int recvPort = 11000;
static private bool receiverConnected;
static private bool receiverReady;
//TODO: set max message size somehow intelligently
private byte[] bytes = new byte[byteCount];
void Start() {
receiverConnected = false;
receiverReady = false;
IPAddress localAddr = IPAddress.Parse("127.0.0.1"); //always locally
listener = new TcpListener(localAddr, recvPort);
listener.Start();
}
// Update is called once per frame
void Update()
{
if (listener.Pending())
{
client = listener.AcceptSocket();
receiverConnected = true;
}
if (receiverConnected)
{
try
{
int bytesRec;
byte[] allBytes = new byte[byteCount];
bytesRec = client.Receive(allBytes);
if (bytesRec == 0)
{
client.Close();
client.Disconnect(false);
receiverReady = false;
receiverConnected = false;
}
else {
bytes = allBytes.Take(bytesRec).ToArray();
receiverReady = true;
}
catch (Exception e)
{
Debug.Log("Exception in receiving and rendering data");
}
}
//now process:
if (receiverConnected && receiverReady)
{
//DO STUFF
}
}
}
在Python方面,我的程序以以下方式启动:
TCP_IP = '127.0.0.1'
TCP_PORT = 11000
BUFFER_SIZE = 1000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
虽然一开始效果不错,但在我关闭python应用程序并重新启动它几次之后,
s.connect((TCP\u IP,TCP\u端口))
开始挂起,程序永远不会继续。我想我对这些连接的处理有问题。我如何才能稍微修改它,以便更优雅地处理关闭和重新打开python端连接请求?关闭套接字的代码在哪里?if(false)
?不知道那该怎么办。您没有关闭插座,这可能就是您出现此问题的原因。请注意,将套接字代码放在Update
函数中不是一个好主意。从Start
函数启动一个新线程,然后将当前套接字代码移动到该新线程。哎呀,添加if(false)是为了调试。我修正了密码。请注意,如果没有这些,情况仍然不好。Unity3D不鼓励使用线程,我希望作为一种解决方案避免使用线程。阿吉安,前几次连接一切正常,但之后一切都失败了。有时它是否有效并不重要。当receiverConnected
为true时,您正在从服务器读取数据。从主线程调用Socket.Receive
,并在Update
函数中调用是非常糟糕的,会阻塞主线程。您必须使用线程或异步方法,如NetworkStream.ReadAsync
。在你做出这些改变之前,你所做的一切都将继续挂起。即使你想在没有线程或异步方法的情况下修复它,你的游戏中也会有一个有趣的帧速率。你走!