Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Weird Networking issue

Discussion in 'Multiplayer' started by fsycdt, Dec 31, 2020.

  1. fsycdt

    fsycdt

    Joined:
    Sep 15, 2020
    Posts:
    7
    I have a Unity host running on a windows machine and a Python client running on a Raspberry Pi on the same LAN Network as unity. The problem is that python code tries to connect to the port but it fails after some time due to timeout.
    What is strange is that the same unity code implemented as a C# console app using visual studio works fine. so the problem is not from data not flowing from Raspberry Pi to the host machine. but also unity works fine when the python code is run on the same host machine. So that rules out problems with the unity code as well I think. I have also tried using the public address of the host machine and still no luck. there are no errors, just python not being able to connect to the port (when the function
    socket.Connect((IP, Port))
    is invoked).

    Unity code:
    Code (CSharp):
    1. using System;
    2. using UnityEngine;
    3. using System.Net.Sockets;
    4. using System.Linq;
    5. using System.Net;
    6. using System.Text;
    7. using System.Threading;
    8. using System.Threading.Tasks;
    9.  
    10. public class ServerManager : MonoBehaviour
    11. {
    12.     public static ManualResetEvent allDone = new ManualResetEvent(false);
    13.  
    14.     CancellationTokenSource tokenSource = new CancellationTokenSource();
    15.     CancellationToken ct;
    16.  
    17.     // Create a TCP/IP socket.
    18.     Socket listener;
    19.  
    20.     Socket clientListener;
    21.     Socket handler;
    22.  
    23.     private void OnApplicationQuit()
    24.     {
    25.         tokenSource.Cancel();
    26.  
    27.         try
    28.         {
    29.             listener.Close();
    30.             clientListener.Close();
    31.             handler.Close();
    32.         }
    33.         catch { }
    34.     }
    35.     // Start is called before the first frame update
    36.     void Start()
    37.     {
    38.         ct = tokenSource.Token;
    39.         StartListening();
    40.     }
    41.  
    42.     public async void StartListening()
    43.     {
    44.         var task = Task.Run(() =>
    45.         {
    46.             // Establish the local endpoint for the socket.
    47.             // The DNS name of the computer
    48.             // running the listener is "host.contoso.com".
    49.             IPAddress ipAddress = IPAddress.Parse("192.168.1.14");
    50.             IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 6666);
    51.  
    52.             // Create a TCP/IP socket.
    53.             listener = new Socket(ipAddress.AddressFamily,
    54.             SocketType.Stream, ProtocolType.Tcp );
    55.  
    56.             // Bind the socket to the local endpoint and listen for incoming connections.
    57.             try
    58.             {
    59.                 listener.Bind(localEndPoint);
    60.                 listener.Listen(100);
    61.  
    62.                 while (true)
    63.                 {
    64.                     // Set the event to nonsignaled state.
    65.                     allDone.Reset();
    66.  
    67.                     // Start an asynchronous socket to listen for connections.
    68.                     //Console.WriteLine("Waiting for a connection...");
    69.                     listener.BeginAccept(
    70.                         new AsyncCallback(AcceptCallback),
    71.                         listener);
    72.  
    73.                     // Wait until a connection is made before continuing.
    74.                     allDone.WaitOne();
    75.                 }
    76.             }
    77.             catch (Exception e)
    78.             {
    79.                 Debug.LogError(e.ToString());
    80.             }
    81.  
    82.             //Console.WriteLine("\nPress ENTER to continue...");
    83.             //Console.Read();
    84.         }, tokenSource.Token);
    85.         await task;
    86.     }
    87.  
    88.     public void AcceptCallback(IAsyncResult ar)
    89.     {
    90.         try
    91.         {
    92.             // Signal the main thread to continue.
    93.             allDone.Set();
    94.  
    95.             // Get the socket that handles the client request.
    96.             clientListener = (Socket)ar.AsyncState;
    97.             handler = listener.EndAccept(ar);
    98.  
    99.             // Create the state object.
    100.             StateObject state = new StateObject();
    101.             state.workSocket = handler;
    102.             handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
    103.                 new AsyncCallback(ReadCallback), state);
    104.         }
    105.         catch (Exception e)
    106.         { }
    107.     }
    108.  
    109.     public void ReadCallback(IAsyncResult ar)
    110.     {
    111.         String content = String.Empty;
    112.  
    113.         // Retrieve the state object and the handler socket
    114.         // from the asynchronous state object.
    115.         StateObject state = (StateObject) ar.AsyncState;
    116.         Socket handler = state.workSocket;
    117.  
    118.         // Read data from the client socket.
    119.         int bytesRead = handler.EndReceive(ar);
    120.  
    121.         if (bytesRead > 0)
    122.         {
    123.             // There  might be more data, so store the data received so far.
    124.             state.sb.Append(Encoding.ASCII.GetString(
    125.                 state.buffer, 0, bytesRead));
    126.  
    127.             // Check for end-of-file tag. If it is not there, read
    128.             // more data.
    129.             content = state.sb.ToString();
    130.             if (content.IndexOf("<EOF>") > -1)
    131.             {
    132.                 // All the data has been read from the
    133.                 // client. Display it on the console.
    134.                 Debug.Log($"Read {content.Length} bytes from socket. \n Data : {content}");
    135.                 // Echo the data back to the client.
    136.                 Send(handler, content);
    137.             }
    138.             else
    139.             {
    140.                 // Not all data received. Get more.
    141.                 handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
    142.                 new AsyncCallback(ReadCallback), state);
    143.             }
    144.         }
    145.     }
    146.  
    147.     private void Send(Socket handler, String data)
    148.     {
    149.         // Convert the string data to byte data using ASCII encoding.
    150.         byte[] byteData = Encoding.ASCII.GetBytes(data);
    151.  
    152.         // Begin sending the data to the remote device.
    153.         handler.BeginSend(byteData, 0, byteData.Length, 0,
    154.             new AsyncCallback(SendCallback), handler);
    155.     }
    156.  
    157.     private void SendCallback(IAsyncResult ar)
    158.     {
    159.         try
    160.         {
    161.             // Retrieve the socket from the state object.
    162.             Socket handler = (Socket) ar.AsyncState;
    163.  
    164.             // Complete sending the data to the remote device.
    165.             int bytesSent = handler.EndSend(ar);
    166.             Debug.Log($"Sent {bytesSent} bytes to client.");
    167.  
    168.             handler.Shutdown(SocketShutdown.Both);
    169.             handler.Close();
    170.  
    171.         }
    172.         catch (Exception e)
    173.         {
    174.             Debug.LogError(e.ToString());
    175.         }
    176.     }
    177. }
    178.  
    179. // State object for reading client data asynchronously
    180. public class StateObject
    181. {
    182.     // Size of receive buffer.
    183.     public const int BufferSize = 1024;
    184.  
    185.     // Receive buffer.
    186.     public byte[] buffer = new byte[BufferSize];
    187.  
    188.     // Received data string.
    189.     public StringBuilder sb = new StringBuilder();
    190.  
    191.     // Client socket.
    192.     public Socket workSocket = null;
    193. }
    Python Code:

    import socket

    TCP_IP = '192.168.1.14'
    TCP_PORT = 6666
    BUFFER_SIZE = 256
    MESSAGE = "Hello, World!<EOF>".encode()
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((TCP_IP, TCP_PORT))
    s.send(MESSAGE)
    data = s.recv(BUFFER_SIZE)
    s.close()
    print("received data:", data)


    And the C# console app code:
    Code (CSharp):
    1. using System;
    2. using System.Net;
    3. using System.Net.Sockets;
    4. using System.Text;
    5. using System.Threading;
    6.  
    7. // State object for reading client data asynchronously
    8. public class StateObject
    9. {
    10.     // Size of receive buffer.
    11.     public const int BufferSize = 256;
    12.  
    13.     // Receive buffer.
    14.     public byte[] buffer = new byte[BufferSize];
    15.  
    16.     // Received data string.
    17.     public StringBuilder sb = new StringBuilder();
    18.  
    19.     // Client socket.
    20.     public Socket workSocket = null;
    21. }
    22.  
    23. public class AsynchronousSocketListener
    24. {
    25.     // Thread signal.
    26.     public static ManualResetEvent allDone = new ManualResetEvent(false);
    27.  
    28.     public AsynchronousSocketListener()
    29.     {
    30.     }
    31.  
    32.     public static void StartListening()
    33.     {
    34.         // Establish the local endpoint for the socket.
    35.         // The DNS name of the computer
    36.         // running the listener is "host.contoso.com".
    37.         IPAddress ipAddress = IPAddress.Parse("192.168.1.14");
    38.         IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 6666);
    39.  
    40.         // Create a TCP/IP socket.
    41.         Socket listener = new Socket(ipAddress.AddressFamily,
    42.             SocketType.Stream, ProtocolType.Tcp );
    43.  
    44.         // Bind the socket to the local endpoint and listen for incoming connections.
    45.         try
    46.         {
    47.             listener.Bind(localEndPoint);
    48.             listener.Listen(100);
    49.  
    50.             while (true)
    51.             {
    52.                 // Set the event to nonsignaled state.
    53.                 allDone.Reset();
    54.  
    55.                 // Start an asynchronous socket to listen for connections.
    56.                 listener.BeginAccept(
    57.                     new AsyncCallback(AcceptCallback),
    58.                     listener);
    59.  
    60.                 // Wait until a connection is made before continuing.
    61.                 allDone.WaitOne();
    62.             }
    63.  
    64.         }
    65.         catch (Exception e)
    66.         {
    67.             Console.WriteLine(e.ToString());
    68.         }
    69.  
    70.         Console.WriteLine("\nPress ENTER to continue...");
    71.         Console.Read();
    72.  
    73.     }
    74.  
    75.     public static void AcceptCallback(IAsyncResult ar)
    76.     {
    77.         // Signal the main thread to continue.
    78.         allDone.Set();
    79.  
    80.         // Get the socket that handles the client request.
    81.         Socket listener = (Socket) ar.AsyncState;
    82.         Socket handler = listener.EndAccept(ar);
    83.  
    84.         // Create the state object.
    85.         StateObject state = new StateObject();
    86.         state.workSocket = handler;
    87.         handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
    88.             new AsyncCallback(ReadCallback), state);
    89.     }
    90.  
    91.     public static void ReadCallback(IAsyncResult ar)
    92.     {
    93.         String content = String.Empty;
    94.  
    95.         // Retrieve the state object and the handler socket
    96.         // from the asynchronous state object.
    97.         StateObject state = (StateObject) ar.AsyncState;
    98.         Socket handler = state.workSocket;
    99.  
    100.         // Read data from the client socket.
    101.         int bytesRead = handler.EndReceive(ar);
    102.  
    103.         if (bytesRead > 0)
    104.         {
    105.             // There  might be more data, so store the data received so far.
    106.             state.sb.Append(Encoding.ASCII.GetString(
    107.                 state.buffer, 0, bytesRead));
    108.  
    109.             // Check for end-of-file tag. If it is not there, read
    110.             // more data.
    111.             content = state.sb.ToString();
    112.             if (content.IndexOf("<EOF>") > -1)
    113.             {
    114.                 // All the data has been read from the
    115.                 // client. Display it on the console.
    116.                 Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
    117.                     content.Length, content);
    118.                 // Echo the data back to the client.
    119.                 Send(handler, content);
    120.             }
    121.             else
    122.             {
    123.                 // Not all data received. Get more.
    124.                 handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
    125.                 new AsyncCallback(ReadCallback), state);
    126.             }
    127.         }
    128.     }
    129.  
    130.     private static void Send(Socket handler, String data)
    131.     {
    132.         // Convert the string data to byte data using ASCII encoding.
    133.         byte[] byteData = Encoding.ASCII.GetBytes(data);
    134.  
    135.         // Begin sending the data to the remote device.
    136.         handler.BeginSend(byteData, 0, byteData.Length, 0,
    137.             new AsyncCallback(SendCallback), handler);
    138.     }
    139.  
    140.     private static void SendCallback(IAsyncResult ar)
    141.     {
    142.         try
    143.         {
    144.             // Retrieve the socket from the state object.
    145.             Socket handler = (Socket) ar.AsyncState;
    146.  
    147.             // Complete sending the data to the remote device.
    148.             int bytesSent = handler.EndSend(ar);
    149.             Console.WriteLine("Sent {0} bytes to client.", bytesSent);
    150.  
    151.             handler.Shutdown(SocketShutdown.Both);
    152.             handler.Close();
    153.  
    154.         }
    155.         catch (Exception e)
    156.         {
    157.             Console.WriteLine(e.ToString());
    158.         }
    159.     }
    160.  
    161.     public static int Main(String[] args)
    162.     {
    163.         StartListening();
    164.         return 0;
    165.     }
    166. }
     
    Last edited: Dec 31, 2020
  2. fsycdt

    fsycdt

    Joined:
    Sep 15, 2020
    Posts:
    7
    All you need to do is just build the and it will work. first time you run the app, windows prompts you to allow access to network which you should do and then it will connect without problem
     
    Last edited: Dec 31, 2020