1

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?

enter image description here

How can I solve this issue?

Cœur
  • 37,241
  • 25
  • 195
  • 267
rrz0
  • 2,182
  • 5
  • 30
  • 65
  • If you listen to `IPAddress.Any` on the server, you must connect to the server with the IP not with the loopback address. Go to cmd, type "ipconfig /all" and obtain the IPAddress of your computer. It should look something like this "192.168.1.8". Use that in your python script instead of "127.0.0.1". Let me now if this fixes your issue. – Programmer May 01 '18 at 11:27
  • Thanks for your helpful comment. Not sure if I understood you correctly but do I also need to change the IPAddress in my C# script too? Unfortunately, the issue persists with the same error message. – rrz0 May 01 '18 at 11:34
  • No. I only asked you to change your python script. You did this but got the-same error? – Programmer May 01 '18 at 11:35
  • Yes, confirmed. – rrz0 May 01 '18 at 11:36
  • 1.Type "Windows Defender Firewall" in the Windows search bar. 2.Open that program and click on "Change Settings" . 3.Scroll down to where it says Unity XX (Anything that starts with Unity) then check the private and public check boxes next to them. Click save to save it. If Unity is not listed, click the "Allow another app.." button then manually add the Unity app there. *Do the-same thing to your client python program.* – Programmer May 01 '18 at 11:41
  • Followed through with the instructions, but the error persists. During my initial testing I had all my firewalls explicitly turned off too. PyCharm was not listed so as mentioned above, I manually added the executable. – rrz0 May 01 '18 at 11:53
  • 1
    Note that if you are running the code with PyCharm, you must also add PyCharm to the allow list too.If you built the python code to exe file, you must also add that exe file to the allow list too. – Programmer May 01 '18 at 11:56
  • 1
    While at it, download [Hercules SETUP utility](https://www.hw-group.com/products/hercules/index_en.html). Use it to connect to your Unity server and see if it will connect. If it works, create a server with Hercules and see if you can connect to it with your python client code. With this, you will know which side of your code is causing the issue. Don't forget to add Hercules to the allow list too. – Programmer May 01 '18 at 11:58
  • 1
    Thanks for the above suggestions. Will try Hercules to narrow down where the error is coming from. – rrz0 May 01 '18 at 12:00

0 Answers0