gpt4 book ai didi

c# - 如何在不关闭 C# 中的 NetworkStream 的情况下发出数据结束信号

转载 作者:太空狗 更新时间:2023-10-29 20:59:34 25 4
gpt4 key购买 nike

我有一个客户端应用程序,它序列化一个对象并将其发送到服务器应用程序。服务器应该反序列化对象,对其进行更改,然后将其序列化并发回。

服务器代码:

TcpClient client = server.AcceptTcpClient();
using(NetworkStream stream = client.GetStream())
{
using(StreamReader streamReader = new StreamReader(stream))
{
string xmlData = streamReader.ReadToEnd();
}
}

除非客户端关闭流,否则 ReadToEnd 不会返回。但是如果客户端关闭流,我就无法发送响应。

有更好的方法吗?

最佳答案

您可以通过仅关闭您那一半的双工 TCP 连接来发出“数据结束”信号。这是通过 Socket.Disconnect 完成的.

看看它是如何与这个例子一起工作的,我保持与你的例子相似。客户端发送数据,然后调用Disconnect;这允许 ReadToEnd 返回同时仍然保持服务器的一半连接打开。然后服务器发送响应并断开连接,之后双方可以关闭他们的连接端以将其断开。

static void Main(string[] args)
{
Action clientCode = () =>
{
var buffer = new byte[100];
var clientSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect(IPAddress.Loopback, 6690);
clientSocket.Send(buffer);
clientSocket.Disconnect(false);
Console.WriteLine("Client: message sent and socket disconnected.");
while (true) {
var bytesRead = clientSocket.Receive(buffer);
if (bytesRead == 0) {
break;
}

Console.WriteLine("Client: read " + bytesRead + " bytes.");
}

clientSocket.Dispose();
};

var server = new TcpListener(IPAddress.Loopback, 6690);
var thread = new Thread(new ThreadStart(clientCode));
server.Start();
thread.Start();
var client = server.AcceptTcpClient();

using(NetworkStream stream = client.GetStream()) {
using(StreamReader streamReader = new StreamReader(stream))
{
var data = streamReader.ReadToEnd();
Console.WriteLine("Server: read " + data.Length + " bytes.");

// Since we 're here we know that the client has disconnected.
// Send the response before StreamReader is disposed, because
// that will cause the socket itself to be closed as well!
Thread.Sleep(TimeSpan.FromSeconds(1));
Console.WriteLine("Server: sending response.");
stream.Write(new byte[10], 0, 10);
Console.WriteLine("Server: closing socket.");
}
}

server.Stop();
Console.WriteLine("Server: waiting for client thread to complete.");
thread.Join();


return;
}

关于c# - 如何在不关闭 C# 中的 NetworkStream 的情况下发出数据结束信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7535901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com