我已经通过TCP套接字多次在应用程序之间发送二进制数据,但从未使用过字符串.陷入了打算这样做的问题.这是我得到的:
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();
Run Code Online (Sandbox Code Playgroud)
如何在不关闭网络流的情况下发送字符串?ns.Flush()是我真正想要的.
你有一个sw.Flush()
,应该工作.一个人WriteLine()
也可能做到了.
但是当另一方做了ReadLine()时,你必须确保以换行结束.尝试WriteLine()而不是Write().
关闭StreamReader/Writer时要小心,它们也会关闭它们的底层流.
归档时间: |
|
查看次数: |
32722 次 |
最近记录: |