Question

I am trying to create a program in order to send and receive strings from another computer on network. There will be only a unique pair of computer connected together through the program. Most of it is done and works perfectly except for the first connection. The first connection can be established only if the two computers are opening the program at the same time. Because the server on the other computer won't be running, hence the connection would be refused. Here is the code :

public MultiplayerState2(Game1 game)
    {
        this.game = game;
        localIp = GetLocalIP();


        server = new TcpListener(IPAddress.Parse(localIp), localPort);


        server.Start();

        networkingThread = new Thread(getData);
        networkingThread.Start();

        clientThread = new Thread(connectClient);
        clientThread.Name = "Connect Client";
        clientThread.Start();
    }

    void connectClient()
    {
        while (client == null)
        {

            try
            {
                client = new TcpClient(remoteIp, remotePort);
                Console.WriteLine("Connected");
                clientThread.Abort();
            }
            catch
            {
                Console.WriteLine("Waiting for partner");

            }
        }

    }

Here, connectClient is supposed to wait for a connection from a computer. But there the only thing that I get as output is waiting for partner. Is this the right way for waiting a connection? And if yes, why isn't it working?

Was it helpful?

Solution

The TcpClient constructor attempts to connect to the server that is listening on the specified port. But this process has a timeout of 1 minute. If the connection do not succeed within 1 minute, it will be closed and an exception will be thrown; hence you are getting the exception.

This is the only way to attempt to connect to server. The only thing you can add is cause the thread to sleep (Thread.Sleep(n)) for some time, like 10 seconds or so (depending on your context).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top