Search Unity

  1. Improved Prefab workflow (includes Nested Prefabs!), 2D isometric Tilemap and more! Get the 2018.3 Beta now.
    Dismiss Notice
  2. The Unity Pro & Visual Studio Professional Bundle gives you the tools you need to develop faster & collaborate more efficiently. Learn more.
    Dismiss Notice
  3. Let us know a bit about your interests, and if you'd like to become more directly involved. Take our survey!
    Dismiss Notice
  4. Improve your Unity skills with a certified instructor in a private, interactive classroom. Watch the overview now.
    Dismiss Notice
  5. Want to see the most recent patch releases? Take a peek at the patch release page.
    Dismiss Notice

Problem with client (android)/server(PC) communication

Discussion in 'Connected Games' started by ABB13, Jun 23, 2018.

  1. ABB13

    ABB13

    Joined:
    Apr 23, 2018
    Posts:
    12
    Hi everyone :)
    I'm working on a Client android app and on a Server software on pc, but when I run these two program the client says me that:
    SocketException: System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it

    Server
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using System.Net.Sockets;
    5. using System.Net;
    6. using System.IO;
    7. using System.Threading;
    8. using System;
    9.  
    10. public class Server : MonoBehaviour {
    11.  
    12.     public int port;
    13.  
    14.     Thread tcpListenerThread;
    15.  
    16.     // Use this for initialization
    17.     void Start () {
    18.  
    19.         Debug.Log("Nello start");
    20.         tcpListenerThread = new Thread(() => ListenfForMessages(port) );
    21.        
    22.     }
    23.    
    24.     // Update is called once per frame
    25.     void Update () {
    26.        
    27.     }
    28.  
    29.     public void ListenfForMessages(int port)
    30.     {
    31.         Debug.Log("inizio Listen");
    32.         TcpListener server = null;
    33.         try
    34.         {
    35.             // Set the TcpListener
    36.             IPAddress localAddr = IPAddress.Parse("127.0.0.1");
    37.  
    38.             server = new TcpListener(localAddr, port);
    39.  
    40.             // Vado in ascolto
    41.             server.Start();
    42.  
    43.             // Buffer per la lettura dei dati
    44.             Byte[] bytes = new Byte[256];
    45.             String data = null;
    46.  
    47.             // Entro nel loop del "listening"
    48.             while (true)
    49.             {
    50.                     Debug.Log("Waiting for a connection... ");
    51.  
    52.                     //
    53.                     TcpClient client = server.AcceptTcpClient();
    54.                     Debug.Log("Connected");
    55.  
    56.                     data = null;
    57.  
    58.                     // Oggetto stream per la lettura e la scrittura
    59.                     NetworkStream stream = client.GetStream();
    60.  
    61.                     int i;
    62.  
    63.                     // Loop per la ricezione dei dati inviati dal client
    64.                     while((i = stream.Read(bytes, 0, bytes.Length)) != 0)
    65.                     {
    66.                         data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
    67.                         Debug.Log(String.Format("Received: {0}", data));
    68.  
    69.                         // Processa i data mandati dal client
    70.                         data = data.ToUpper();
    71.  
    72.                         byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
    73.  
    74.                         // Ritorno una risposta
    75.                         stream.Write(msg, 0, msg.Length);
    76.                         Debug.Log(String.Format("Sent: {0}", data));
    77.                         Debug.Log("Sto qui dentro :D ");
    78.  
    79.                     }
    80.                 // Chiduo la connessione con il client
    81.                 client.Close();
    82.             }
    83.         }
    84.         catch (SocketException e)
    85.         {
    86.             Debug.LogError(String.Format("SocketException: {0}", e));
    87.            
    88.         }
    89.         finally
    90.         {
    91.             server.Stop();
    92.         }
    93.     }
    94. }
    95.  



    Client
    Code (CSharp):
    1. using System;
    2. using System.Net.Sockets;
    3. using System.Collections;
    4. using System.Collections.Generic;
    5. using UnityEngine;
    6. using System.Net;
    7.  
    8. public class Client : MonoBehaviour {
    9.  
    10.     public string server;
    11.     public int port;
    12.  
    13.     // Use this for initialization
    14.     void Start ()
    15.     {
    16.         Debug.Log("START");
    17.         // Connettersi con il server
    18.         SendMessageToServer("Connessione effettuata");
    19.      
    20.     }
    21.  
    22.     // Update is called once per frame
    23.     void Update ()
    24.     {
    25.         // ricevere informazioni dal server
    26.      
    27.     }
    28.  
    29.     public void SendMessageToServer(string message)
    30.     {
    31.         Debug.Log("In send message");
    32.         ConnectToServer (server, port, message);
    33.     }
    34.  
    35.     void ConnectToServer(string server, int port, string message)
    36.     {
    37.         Debug.Log("nel connect");
    38.         try
    39.         {
    40.             Debug.Log("NEL TRY");
    41.             TcpClient client = new TcpClient(server, port);
    42.  
    43.             // Traduce il messaggio mandato in caratteri ASCII
    44.             Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
    45.  
    46.             // Così si aprirà uno stream per il client per scrivere e legggere
    47.             NetworkStream stream = client.GetStream();
    48.  
    49.             // Manda il messaggio per connettersi al Server TCP
    50.             stream.Write(data, 0, data.Length);
    51.  
    52.             Debug.Log(String.Format("Sent: {0}", message));
    53.  
    54.             // Riceve il risponso dal server
    55.  
    56.             // Buffer per immagazinare il responso
    57.             data = new Byte[256];
    58.  
    59.             // String per immagazinare il responso nella rappresentazione ASCII
    60.             String responseData = String.Empty;
    61.  
    62.             // Leggi i rimi batch dal responso del server
    63.             Int32 bytes = stream.Read(data, 0, data.Length);
    64.             responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
    65.             Debug.Log(String.Format("Receoved: {0}", responseData));
    66.  
    67.             // Chiusura
    68.             stream.Close();
    69.             client.Close();
    70.         }
    71.         catch (ArgumentNullException e)
    72.         {
    73.             Debug.LogError(String.Format("ArgumentNullException: {0}", e));
    74.         }
    75.             catch (SocketException e)
    76.             {
    77.                     Debug.LogError(String.Format("SocketException: {0}", e));          
    78.             }
    79.     }
    80.  
    81. }
    82.  

    Could someone help me up, please?
     
  2. ABB13

    ABB13

    Joined:
    Apr 23, 2018
    Posts:
    12
    Is there someone who can help me?
     
  3. ABB13

    ABB13

    Joined:
    Apr 23, 2018
    Posts:
    12
  4. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    3,593
    I've never used tcpListener, but I'm pretty sure having the Windows server listen for connections on its own loopback address (127.0.0.1) will result in only clients running on that same computer being able to connect.

    Otherwise you also need to make sure your Windows software firewall settings are not blocking connections as well.
     
  5. KevinHGS

    KevinHGS

    Joined:
    May 29, 2017
    Posts:
    11
  6. ABB13

    ABB13

    Joined:
    Apr 23, 2018
    Posts:
    12
    Hi Kevin thanks for the help :)
    Sorry for my absence.

    I try the LLAPI but I get this error:
    Attempt to send to not connected connection {1}
    UnityEngine.Networking.NetworkTransport:Send(Int32, Int32, Int32, Byte[], Int32, Byte&)

    There's my code:
    Server
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using System.Net.Sockets;
    5. using System.Net;
    6. using System.IO;
    7. using System.Threading;
    8. using System;
    9. using UnityEngine.Networking;
    10. using UnityEngine.UI;
    11. using System.Runtime.Serialization.Formatters.Binary;
    12.  
    13. public class Server : MonoBehaviour {
    14.  
    15.     public Text errorText;
    16.     public Text errorTextD;
    17.  
    18.     byte myReliableChannelId;
    19.     int socketId; // above Start()
    20.     int socketPort = 8888; // Also a class member variable
    21.  
    22.  
    23.     void Start()
    24.     {
    25.         // Inizializzo il socket per poter ascoltare e ammettere connessioni
    26.         ConnectionConfig config = new ConnectionConfig();
    27.  
    28.          myReliableChannelId = config.AddChannel(QosType.Reliable);
    29.    
    30.         int maxConnections = 10;
    31.           HostTopology topology = new HostTopology(config, maxConnections);
    32.         NetworkTransport.Init();
    33.         socketId = NetworkTransport.AddHost(topology, socketPort);
    34.         Debug.Log("Socket Open. SocketId is: " + socketId);
    35.        
    36.  
    37.     }// close start()
    38.  
    39.     // Nell'Update ci sarà quel che servirà per la ricezione dei messaggi
    40.     void Update()
    41.     {
    42.         int outHostId;
    43.         int outConnectionId;
    44.         int outChannelId;
    45.         byte[] recBuffer= new byte[1024];
    46.         int dataSize;
    47.         byte error;
    48.         NetworkEventType recNetworkEvent = NetworkTransport.Receive(out outHostId, out outConnectionId, out outChannelId, recBuffer, recBuffer.Length, out dataSize, out error);
    49.         NetworkError ne = (NetworkError)error;
    50.  
    51.         switch (recNetworkEvent)
    52.         {
    53.             case NetworkEventType.Nothing:
    54.                 break;
    55.             case NetworkEventType.ConnectEvent:
    56.                 errorTextD.text = errorTextD.text + "Incoming connection event received \n" + ne.ToString() ;
    57.                 Debug.Log("Incoming connection event received");
    58.                 break;
    59.             case NetworkEventType.DataEvent:
    60.                 Stream stream = new MemoryStream(recBuffer);
    61.                 BinaryFormatter formatter = new BinaryFormatter();
    62.                 string message = formatter.Deserialize(stream) as string;
    63.                 errorTextD.text = errorTextD.text + "incoming message event received: " + message + "\n";
    64.                 Debug.Log("incoming message event received: " + message);
    65.                 break;
    66.             case NetworkEventType.DisconnectEvent:
    67.                 Debug.Log("remote client event disconnected");
    68.                 break;
    69.             default:
    70.                 //Output the error
    71.                 errorTextD.text = "Unknown network message type received: " + recNetworkEvent;
    72.                 Debug.LogError("Unknown network message type received: " + recNetworkEvent);
    73.                 break;
    74.         }
    75.    
    76.     }
    77.  
    78. }
    Client
    Code (CSharp):
    1. using System;
    2. using System.Net.Sockets;
    3. using System.Collections;
    4. using System.Collections.Generic;
    5. using UnityEngine;
    6. using System.Net;
    7. using System.IO;
    8. using UnityEngine.UI;
    9. using UnityEngine.Networking;
    10. using System.Runtime.Serialization.Formatters.Binary;
    11.  
    12. public class Client : MonoBehaviour
    13. {
    14.     public Text textView;
    15.     int connectionId;
    16.     int socketId;
    17.     int socketPort = 54321;
    18.     int myReliableChannelId;
    19.  
    20.  
    21.     void Start()
    22.     {
    23.         ConnectionConfig config = new ConnectionConfig();
    24.  
    25.          myReliableChannelId = config.AddChannel(QosType.Reliable);
    26.         HostTopology topology = new HostTopology(config, 10);
    27.         NetworkTransport.Init();
    28.         socketId = NetworkTransport.AddHost(topology);
    29.         Debug.Log("Socket Open. SocketId is: " + socketId);
    30.         GoConnect();
    31.     }
    32.  
    33.     public void GoConnect()
    34.     {
    35.         byte error;
    36.           connectionId = NetworkTransport.Connect(socketId, "127.0.0.1" , socketPort, 0, out error);
    37.          if ((NetworkError)error != NetworkError.Ok)
    38.         {
    39.             Debug.Log("Error: " + (NetworkError)error);
    40.         }
    41.         SendSocketMessage();      
    42.     }
    43.  
    44.     // Questa function invierà i messaggi al client
    45.     public void SendSocketMessage()
    46.     {
    47.         byte error;
    48.         byte[] buffer = new byte[1024];
    49.         Stream stream = new MemoryStream(buffer);
    50.         BinaryFormatter formatter = new BinaryFormatter();
    51.         formatter.Serialize(stream, "HelloServer");
    52.  
    53.         NetworkTransport.Send(socketId, connectionId, myReliableChannelId, buffer, (int)stream.Position, out error);
    54.         Debug.Log("ERROR IS: " + (NetworkError)error);
    55.  
    56.     }
    57. }
    I don't understand what is the problem :/

    P.S. Let me tell you that these two files are linked on 2 different project
     
  7. KevinHGS

    KevinHGS

    Joined:
    May 29, 2017
    Posts:
    11
    Hi @ABB13,
    oh, you must received the ConnectEvent (ensure the connection is ok) in client before you send the message to the server.

    Receive the message from host:

    Code (CSharp):
    1. protected virtual void Receive()
    2.         {
    3.             if (!IsConnected && !IsConnecting)
    4.                 return;
    5.  
    6.             if (!NetworkUtility.IsValidHostId(HostId))
    7.                 return;
    8.  
    9.             NetworkEventType networkEvent;
    10.             do
    11.             {
    12.  
    13.                 int connectionId;
    14.                 int channelId;
    15.                 int receivedSize;
    16.                 byte error;
    17.  
    18.                 networkEvent = NetworkTransport.ReceiveFromHost(HostId
    19.                     , out connectionId, out channelId
    20.                     , _buffer, _buffer.Length
    21.                     , out receivedSize, out error
    22.                 );
    23.  
    24. /*#if UNITY_EDITOR
    25.                 Debug.Log("[" + GetType().Name + "] => Receive => Network Event: " + networkEvent);
    26. #endif*/
    27.  
    28.                 switch (networkEvent)
    29.                 {
    30.                     case NetworkEventType.DataEvent:
    31.                         {
    32.                             OnData(connectionId, channelId, receivedSize, (NetworkError)error);
    33.                             break;
    34.                         }
    35.                     case NetworkEventType.ConnectEvent:
    36.                         {
    37.                             OnConnect(connectionId, (NetworkError)error);
    38.                             break;
    39.                         }
    40.                     case NetworkEventType.DisconnectEvent:
    41.                         {
    42.                             OnDisconnect(connectionId, (NetworkError)error);
    43.                             break;
    44.                         }
    45.                     case NetworkEventType.Nothing:
    46.                         {
    47.                             break;
    48.                         }
    49.                     default:
    50.                         {
    51.                             _logger.Error(LogCategory.Network, "Unknown network message type received: " + networkEvent);
    52.                             break;
    53.                         }
    54.                 } // end witch
    55.             } while (networkEvent != NetworkEventType.Nothing);
    56.         }
    On Connected:

    Code (CSharp):
    1. protected virtual void OnConnect(int connectionId, NetworkError error)
    2.         {
    3.             if (ConnectionId != connectionId)
    4.                 return;
    5.  
    6.             if (error != NetworkError.Ok)
    7.             {
    8.                 _logger.Error(LogCategory.Network, string.Format("Error on ConnectEvent. ConnectionId: {0}, error: {1}", ConnectionId, error));
    9.                 return;
    10.             }
    11.  
    12.             this.IsConnecting = false;
    13.             this.IsConnected = true;
    14.  
    15. #if UNITY_EDITOR
    16.             { // retrieve connection info
    17.                 int port;
    18.                 NetworkID networkId;
    19.                 NodeID nodeId;
    20.                 byte getConnInfoError;
    21.                 string address;
    22.                 NetworkTransport.GetConnectionInfo(HostId, ConnectionId, out address, out port, out networkId, out nodeId, out getConnInfoError);
    23.  
    24.                 _logger.Debug(LogCategory.Network, "[" + GetType().Name + "] => Connection: " + connectionId + ", address: " + address + ", port: " + port
    25.                     + ", Network ID: " + networkId + ", Node ID: " + nodeId
    26.                     + ", Error: " + getConnInfoError);
    27.             }
    28. #endif
    29.  
    30.             this.Port = NetworkTransport.GetHostPort(HostId);
    31.  
    32.             Peer = OnCreatePeer(this.ConnectionId);
    33.             Peer.OnConnected();
    34. #if UNITY_EDITOR
    35.             _logger.Debug(LogCategory.Network, "[" + GetType().Name + "] => Connect to server[" + ServerIp + "], port: " + ServerPort + ", local port: " + this.Port + " ...... OK!");
    36. #endif
    37.             OnConnected();
    38.         }
     
  8. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    3,593
    With the recent announcement that the Unet LLAPI is deprecated and scheduled to be removed from Unity after 2018.4, since you just moved over to it a few weeks ago I'd suggest dropping it and going with something else.