2 つのクライアントと 1 つのサーバーの 3 つのアプリが同時に実行されます。システム全体は次のように機能する必要があります。
- クライアントはシリアル化されたオブジェクトをサーバーに送信し、サーバーはそのオブジェクトをストリームとして受信し、最後に別のクライアントがサーバーからそのストリームを取得して逆シリアル化します。
これは送信者です:
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);
送信者とサーバーのみを実行し、サーバーを確認すると、サーバーはデータを正しく受信します。問題は、レシーバーを実行すると、すべてが切断されることです。だから私の問題はどこですか?誰でも私を指摘できますか?ありがとう