0

I am trying to write a program in Unity3D that can receive and visualize data from a Python application:

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

        }
    }


}

On the Python side, my program starts up with the following:

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))

While this works fine at first, after I close my python application and restart it a few times, s.connect((TCP_IP, TCP_PORT)) begins to hang and the program never continues. I assume there is something wrong in my C# handling of these connections. How can I modify it only a little bit in order to handle closing and re-opening python-side connection requests more gracefully?

user650261
  • 2,115
  • 5
  • 24
  • 47
  • where is the code to close the sockets? – akshat May 16 '18 at 06:22
  • 1
    `if (false)`? Not sure what that's supposed to do. You didn't close the socket and that's likely why you have this issue. Note that it's not a good idea to put that socket code in the `Update` function. Start a new Thread from the `Start` function then move the current socket code to that new Thread. – Programmer May 16 '18 at 06:26
  • Oops, the if (false) was added in for debugging purposes. I fixed the code. Note that without that things are still not okay. Threading is discouraged in Unity3D and I'd like to avoid that as a solution. Agian, things are fine for the first few connects, but after that things fail. – user650261 May 16 '18 at 06:58
  • *"Threading is discouraged in Unity3D and I'd like to avoid that as a solution"* You have to be careful where you get your information or even take time reading the whole thing. Threading is only discouraged *when it is used where it is not needed*. One example is new Unity users using Threading to wait in a script or to create a timer which should be done with a coroutine. – Programmer May 16 '18 at 07:39
  • 1
    It doesn't matter if it works or not sometimes. You are reading from a server when `receiverConnected` is true. Calling `Socket.Receive` from the main Thread and in the `Update` function is awful and will block the main Thread. *You have to use Thread or the Async methods like `NetworkStream.ReadAsync`*. Until you make these changes, whatever you do will continue to hang. Even if you mange to fix it without Thread or the Async methods, expect a funny frame-rate in your game. – Programmer May 16 '18 at 07:46
  • Do you think you could provide a very short example of what you would do? – user650261 May 16 '18 at 07:53
  • 1
    [Here](https://stackoverflow.com/questions/36526332/simple-socket-server-in-unity/36526634#36526634) you go! – Programmer May 16 '18 at 14:15
  • This solution works. If you can write a quick explanation I can accept your response. – user650261 May 16 '18 at 17:32

0 Answers0