问题描述
使用我的代码,我可以在服务器上读取信息,并从客户端写。但我不能够写入从服务器的响应,并在客户端读取。
With my code I can read a message on the server and write from the client. But I am not being able to write a response from the server and read in the client.
客户端上的代码
var cli = new TcpClient();
cli.Connect("127.0.0.1", 6800);
string data = String.Empty;
using (var ns = cli.GetStream())
{
using (var sw = new StreamWriter(ns))
{
sw.Write("Hello");
sw.Flush();
//using (var sr = new StreamReader(ns))
//{
// data = sr.ReadToEnd();
//}
}
}
cli.Close();
上的代码服务器
tcpListener = new TcpListener(IPAddress.Any, port);
tcpListener.Start();
while (run)
{
var client = tcpListener.AcceptTcpClient();
string data = String.Empty;
using (var ns = client.GetStream())
{
using (var sr = new StreamReader(ns))
{
data = sr.ReadToEnd();
//using (var sw = new StreamWriter(ns))
//{
// sw.WriteLine("Hi");
// sw.Flush();
//}
}
}
client.Close();
}
我怎样才能让服务器响应读取数据后,使客户端读取这些数据?
How can I make the server reply after reading the data and make the client read this data?
推荐答案
由于您使用的
TcpClient client = tcpListener.AcceptTcpClient();
,你可以写回客户端直接内无需自我认同。 你的代码将实际工作如果您使用 Stream.Read()
或 .ReadLine()
而不是 .ReadToEnd()
。 ReadToEnd的()
将阻止永远都在网络流,直到流被关闭。请参见以类似的问题,或者从,
, you can write back to the client directly without needing it to self-identify. The code you have will actually work if you use Stream.Read()
or .ReadLine()
instead of .ReadToEnd()
. ReadToEnd()
will block forever on a network stream, until the stream is closed. See this answer to a similar question, or from MSDN,
ReadToEnd的假设,当它已经到头了流
知道。对于其中的
服务器发送的数据,只有当你问
它并不会关闭
连接
交互协议,ReadToEnd的可能会阻止
无限期因为它不达到
结束,应尽量避免。
如果您在一侧使用的ReadLine(),您将需要使用的WriteLine() - 未写() - 在另一侧。另一种方法是使用一个循环调用Stream.Read(),直到有一无所有阅读。你可以看到这是一个完整的例子在的 AcceptTcpClient()文档。相应的客户端的例子是在
If you use ReadLine() at one side, you will need to use WriteLine() - not Write() - at the other side. The alternative is to use a loop that calls Stream.Read() until there is nothing left to read. You can see a full example of this for the server side in the AcceptTcpClient() documentation on MSDN. The corresponding client example is in the TcpClient documentation.
这篇关于如何发送"你好"服务器和回复A"喜"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!