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?