I am trying to utilize Socket connections to send data from my python script (Python 3.6.3) in PyCharm to my C# script in Unity3D.
Something very similar to: https://www.youtube.com/watch?v=eI3YRluluR4
Following the documentation, the below script should work well
Python script:
import socket
host, port = "127.0.0.1", 25001
data = "hello"
# SOCK_STREAM means a TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to server and send data
sock.connect((host, port))
sock.sendall(data.encode("utf-8"))
data = sock.recv(1024).decode("utf-8")
print(data)
finally:
sock.close()
C# script:
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;
using System.Threading;
public class networkCon : MonoBehaviour
{
Thread mThread;
public string connectionIP = "127.0.0.1";
public int connectionPort = 25001;
IPAddress localAdd;
TcpListener listener;
TcpClient client;
Vector3 pos = Vector3.zero;
bool running;
private void Start()
{
ThreadStart ts = new ThreadStart(GetInfo);
mThread = new Thread(ts);
mThread.Start();
}
public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new System.Exception("No network adapters with an IPv4 address in the system!");
}
void GetInfo()
{
localAdd = IPAddress.Parse(connectionIP);
listener = new TcpListener(IPAddress.Any, connectionPort);
listener.Start();
client = listener.AcceptTcpClient();
running = true;
while (running)
{
Connection();
}
listener.Stop();
}
void Connection()
{
NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
string dataReceived = Encoding.UTF8.GetString(buffer, 0, bytesRead);
if (dataReceived != null)
{
if (dataReceived == "stop")
{
running = false;
}
else
{
pos = 10f * StringToVector3(dataReceived);
print("moved");
nwStream.Write(buffer, 0, bytesRead);
}
}
}
However, when running the Python script I keep on getting:
line 11, in sock.connect((host, port)) ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it.
- Domain network firewall is off
- Private network firewall is off
- Public network firewall is off
A similar question has this answer, however I do not think this applies in my case. Could there be some setting from PyCharm editor which needs changing?
How can I solve this issue?