如何在信号端数据,而无需在C#中关闭的NetworkStream [英] How To Signal End Of Data Without Closing NetworkStream in C#

查看:139
本文介绍了如何在信号端数据,而无需在C#中关闭的NetworkStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a client application that serializes a object and sends it to a server application. The server should deserialize the object, make changes to it, then serialize it and send it back.

服务器code:

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

的ReadToEnd不返回,除非客户机关闭流。但是,如果客户端关闭流,我不能发送响应。

The ReadToEnd doesn't return unless the client closes the stream. But if the client closes the stream, I can't send a response.

有没有更好的方式来做到这一点?

Is there a better way to do this?

推荐答案

您可以用信号数据结束通过关闭双工TCP连接的只是你的一半。这是通过<一个href="http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.disconnect.aspx"><$c$c>Socket.Disconnect.

You can signal "end of data" by closing only your half of the duplex TCP connection. This is accomplished with Socket.Disconnect.

请参阅如何与这个例子中,我一直与你相似。客户端发送的数据,然后调用断开;这使得 ReadToEnd 返回,同时仍保持服务器的半连接打开的的。然后,服务器发送一个响应,并断开,之后双方都可以关闭的连接他们的最终将其摧毁。

See how it works with this example, which I kept similar to yours. The client sends the data and then calls Disconnect; this allows ReadToEnd to return while still keeping the server's half of the connection open. The server then sends a response and also disconnects, after which both parties can Close their end of the connection to tear it down.

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#中关闭的NetworkStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆