Concurrent connections in C# socket

Posted by Chu Mai on Stack Overflow See other posts from Stack Overflow or by Chu Mai
Published on 2012-11-06T16:58:37Z Indexed on 2012/11/06 16:59 UTC
Read the original article Hit count: 182

Filed under:
|

There are three apps run at the same time, 2 clients and 1 server. The whole system should function as following:

  • The client sends an serialized object to server then server receives that object as a stream, finally the another client get that stream from server and deserialize it.

This is the sender:

            TcpClient tcpClient = new TcpClient();
            tcpClient.Connect("127.0.0.1", 8888);

            Stream stream = tcpClient.GetStream();
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            binaryFormatter.Serialize(stream, event); // Event is the sending object

            tcpClient.Close();

Server code:

        TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 8888);
        listener.Start(); 
        Console.WriteLine("Server is running at localhost port 8888 ");

        while (true)
        {
            Socket socket = listener.AcceptSocket();
            try 
            {
                Stream stream = new NetworkStream(socket);
                // Typically there should be something to write the stream
                // But I don't knwo exactly what should the stream write
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
                Console.WriteLine("Disconnected: {0}", socket.RemoteEndPoint);
            }
        }

The receiver:

        TcpClient client = new TcpClient();
        // Connect the client to the localhost with port 8888
        client.Connect("127.0.0.1", 8888);
        Stream stream = client.GetStream();
        Console.WriteLine(stream);

when I run only the sender and server, and check the server, server receives correctly the data. The problem is when I run the receiver, everything is just disconnected. So where is my problem ? Could anyone point me out ? Thanks

© Stack Overflow or respective owner

Related posts about c#

Related posts about sockets