C#套接字中的并发连接

时间:2012-11-06 16:58:37

标签: c# sockets

同时运行三个应用程序,2个客户端和1个服务器。整个系统的功能如下:

  • 客户端将一个序列化对象发送到服务器,然后服务器将该对象作为流接收,最后另一个客户端从服务器获取该流并对其进行反序列化。

这是发件人:

            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();

服务器代码:

        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);
            }
        }

接收者:

        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);

当我只运行发件人和服务器,并检查服务器时,服务器正确接收数据。问题是当我运行接收器时,一切都刚刚断开。那我的问题在哪里?有人能指出我吗?谢谢

0 个答案:

没有答案