Search code examples
windowsunity-game-enginenetwork-programmingtcptcplistener

TCP connection in Unity


I'm working on TCP connection between two Windows10 laptops. I made the applications using Unity 2019.2.17f1. However, the TCP connection doesn't work. The Client application connects to the server only when I don't run the server application (this is strange though...), otherwise the client application shows the message "server is not found...".

I put the part of the codes here. Client Program:

public class TCPClientManager : MonoBehaviour
    {
    // ip address(server) and port number
    public string ipAddress = "192.0.0.1";
    public int port = 3000;

    private TcpClient m_tcpClient;
    private NetworkStream m_networkStream;
    private bool m_isConnection;

    private string message;

    void Start()
    {
        try
        {
            // connect to the server 
            m_tcpClient = new TcpClient(ipAddress, port);
            m_networkStream = m_tcpClient.GetStream();
            m_isConnection = true;
        }
        catch (SocketException)
        {
            m_isConnection = false;
            // show a error message
            // ...
        }
    }

    void OnGUI()
    {
        if (m_isConnection)
        {
            GUILayout.Label("server is not found...");
            return;
        }

        // some codes here
    }

    // some codes here
  }

Server Program:

public class TCPServerManager : MonoBehaviour
{
    // ip address(server) and port number
    public string ipAddress = "192.0.0.1";
    public int port = 3000;

    private TcpListener m_tcpListener;
    private TcpClient m_tcpClient;
    private NetworkStream m_networkStream;
    private bool m_isConnection;

    private string message = string.Empty; 

    private void Awake()
    {
        Task.Run(() => OnProcess());
    }

    private void OnProcess()
    {
        var n_IpAddress = IPAddress.Parse(ipAddress);
        m_tcpListener = new TcpListener(n_IpAddress, port);
        m_tcpListener.Start();

        m_tcpClient = m_tcpListener.AcceptTcpClient();

        m_networkStream = m_tcpClient.GetStream();

        while (true)
        {
            var buffer = new byte[256];
            var count = m_networkStream.Read(buffer, 0, buffer.Length);

            if (count == 0)
            {
                OnDestroy();

                Task.Run(() => OnProcess());

                break;
            }

            message += Encoding.UTF8.GetString(buffer, 0, count) + "\n";
        }
    }

    // ....
}

Thank you very much for your comments in advice.


Solution

  • I think you inverted you m_isConnection variables values. You set it to true after connecting the server and false if not. But in OnGUI, if you found the connection then you print an error message and leave. Which means you do your //some code here only if no server was found.