无法连接超过X次的套接字

时间:2018-05-16 06:20:08

标签: 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 {


    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_IP, TCP_PORT))开始挂起,程序永远不会继续。我假设我的C#处理这些连接有问题。我怎样才能稍微修改它以便更优雅地处理关闭和重新打开python-side连接请求?

0 个答案:

没有答案