三个应用程序同时运行,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);
当我只运行发送方和服务器并检查服务器时,服务器正确接收数据。问题是当我运行接收器时,一切都断开了。那么我的问题在哪里?谁能指出我?谢谢