Sunday, April 17, 2011

Client/Server both give up after 1 connection

I'm writing a client/server (as many of you probably already know!). The server is going to be sending data to the client. However, the client can connect once and after that it never attempts to connect again once the connection has been terminated. Similarly, once the server has sent it's message it will ignore future attempts to connect.

Server:

public Server(String p)
    {
        path = p;
        listener = new TcpListener(IPAddress.Any, 1337);
        listener.Start();
        Thread t = new Thread(new ThreadStart(ListenForClients));
        t.IsBackground = true;
        t.Start();
    }

    private void ListenForClients()
    {
        TcpClient client = listener.AcceptTcpClient();
        new Thread(new ParameterizedThreadStart(HandleClientCom)).Start(client);
    }

    private void HandleClientCom(object TcpClient)
    {
        new Dialog("Connection", "Connection established.");
        TcpClient client = (TcpClient)TcpClient;
        NetworkStream stream = client.GetStream();
        //SslStream stream = new SslStream(client.GetStream());
        //stream.AuthenticateAsServer(new X509Certificate(path + "\\ServerCert.cer"));

        ASCIIEncoding encoder = new ASCIIEncoding();
        String str = "This is a long piece of text to send to the client.";
        byte[] bytes = encoder.GetBytes(str);

        stream.Write(bytes, 0, bytes.Length);
        stream.Flush();
    }

Client:

public TCP(BackgroundWorker b)
    {
        try
        {
            bw = b;
            client = new TcpClient();
            IPEndPoint server = new IPEndPoint(IPAddress.Parse(srv), 1337);
            client.Connect(server); //Connect to the server
            bw.ReportProgress(0);   //Update the GUI with the connection status

            Thread t = new Thread(new ParameterizedThreadStart(HandleComms));
            t.IsBackground = true;
            t.Start(client);
        }
        catch (Exception ex)
        {
            lastException = ex;
        }
    }

    public void HandleComms(object c)
    {
        Boolean keepListening = true;
        TcpClient client = (TcpClient)c;
        NetworkStream stream = client.GetStream();
        //stream = new SslStream(client.GetStream());
        //stream.AuthenticateAsClient(srv);

        byte[] msg = new byte[4096]; ;
        int bytesRead = 0;

        while (keepListening)
        {
            try
            {
                bytesRead = stream.Read(msg, 0, 4096);
            }
            catch (Exception ex)
            {
                lastException = ex;
            }

            if (bytesRead > 0)
            {
                StreamWriter writer = new StreamWriter("C:\\Users\\Chris\\Desktop\\ClientLog.txt");
                ASCIIEncoding encoder = new ASCIIEncoding();
                rx = encoder.GetString(msg);
                writer.WriteLine(rx);
                keepListening = false;
                writer.Close();
            }
        }
    }

Sorry for huge amounts of code. Can anyway point out where I've gone wrong?

From stackoverflow
  • Once you've accepted the connection, you'll need to begin listening again.

    Try just making this change:

    private void ListenForClients()
    {
        while(true)
        {
            TcpClient client = listener.AcceptTcpClient();
            new Thread(new ParameterizedThreadStart(HandleClientCom)).Start(client);
        }
    }
    
    Bailz : Absolutely spot on!

0 comments:

Post a Comment