简体   繁体   English

通过tcp网络流读/写字符串

[英]read/write string over tcp network stream

I have been sending binary data between applications lots of times over TCP sockets but never before using strings. 我已经通过TCP套接字多次在应用程序之间发送二进制数据,但从未使用过字符串。 Bumbed into an issue intending to do so. 陷入了打算这样做的问题。 Here is what I got: 这是我得到的:

        TcpClient tcpClient = new TcpClient("localhost", port);

        //Connects fine
        NetworkStream ns = tcpClient.GetStream();
        StreamWriter sw = new StreamWriter(ns);

        //The code moves on but nothing seems to be sent unless I do
        //a sw.Close() after this line. That would however close the  
        //ns and prevent me from reading the response further down
        sw.Write("hello");

        //I am using a stream reader with ReadToEnd() on the tcpListener
        //which never receives the string from this piece of code

        //Since the above never actually send I get stuck here
        string response = new StreamReader(ns).ReadToEnd();

        sw.Close();
        tcpClient.Close();

How do I send the string without closing the network stream? 如何在不关闭网络流的情况下发送字符串? ns.Flush() is what I would be looking for really. ns.Flush()是我真正想要的。

You have an sw.Flush() , that ought to work. 你有一个sw.Flush() ,它应该工作。 A WriteLine() might have done it too. WriteLine()也可能已经完成了。

But when the other side does a ReadLine() then you have to make sure you end with newline. 但是当另一方做了ReadLine()时,你必须确保以换行结束。 Try WriteLine() instead of Write(). 尝试WriteLine()而不是Write()。

And be careful about closing a StreamReader/Writer, they also close their underlying streams. 关闭StreamReader / Writer时要小心,它们也会关闭它们的底层流。

There's a StreamWriter.Flush() . 有一个StreamWriter.Flush() When you get done with sending you message, just do sw.Flush() . 完成向您发送消息后,只需执行sw.Flush() However, since buffer sizes are fairly large (upto a couple KB), the correct way is to only Flush() just before you wait for a response. 但是,由于缓冲区大小相当大(最多几KB),正确的方法是在等待响应之前只Flush() That way several calls to .Write() can be bundled into a single packet and sent down the wire at the same time. 这样,对.Write()几次调用可以捆绑到一个数据包中,同时在线路上发送。

您只需要将StreamWriter上的AutoFlush属性设置为true即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM