我正在尝试与服务器通信。
这是我的简单代码:
System.Net.Sockets.TcpClient sock = new System.Net.Sockets.TcpClient();
string outputString = string.Empty;
sock.Connect("stack.overflow", 80);
NetworkStream ns = null;
StreamReader sr = null;
StreamWriter sw = null;
ns = sock.GetStream();
sr = new StreamReader(ns);
sw = new StreamWriter(ns) { NewLine = "\r\n", AutoFlush = true };
ns.ReadTimeout = 10;
sw.WriteLine("send data to server");
sw.Flush();
outputString = sr.ReadLine();
while (!string.IsNullOrEmpty(outputString))
{
System.Diagnostics.Debug.WriteLine(outputString);
outputString = sr.ReadLine();
}
(我知道我的代码有改进的余地。它让我的测试变得简单)
ReadLine()旁边的一切正常。 它没有做我期望它做的事情。
它从服务器读取所有行,在最后一行之后它无休止地等待新行。至少对我而言似乎在等待。
我认为它会在最后一行之后停止并返回null或其他内容。
有人可以解释一下,从服务器获取所有线路并继续前进的最佳做法是什么?
答案 0 :(得分:0)
public class ServerHandler
{
private BackgroundWorker serverWorker = new BackgroundWorker();
public event EventHandler ServerResponse;
private TcpClient socket;
private NetworkStream networkStream;
private StreamReader streamReader;
private StreamWriter streamWriter;
public ServerHandler()
{
System.Net.Sockets.TcpClient sock = new System.Net.Sockets.TcpClient();
serverWorker.WorkerSupportsCancellation = true;
serverWorker.DoWork += new DoWorkEventHandler(serverWorker_DoWork);
}
public void ConnectToServer()
{
socket = new TcpClient();
socket.Connect("stack.overflow", 80);
networkStream = socket.GetStream();
streamReader = new StreamReader(networkStream);
streamWriter = new StreamWriter(networkStream) { NewLine = "\r\n", AutoFlush = true };
SendMessage("some data");
}
public bool IsConnected
{
get { return socket.Connected; }
}
public void StartListening()
{
if (ServerResponse == null)
throw new Exception("There is no event to intercept the response!");
serverWorker.RunWorkerAsync();
}
private void SendMessage(string message)
{
streamWriter.WriteLine(message);
streamWriter.Flush();
}
private void serverWorker_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
while (true)
{
string serverResponse = streamReader.ReadLine();
ServerResponse(serverResponse, new EventArgs());
}
}
}
就像willaien已经说过的那样,流不知道它何时结束。只要您与服务器通信,就可以等待响应。
我将监听服务器的代码放在后台工作程序中,当出现新响应时,该代码始终侦听并发送事件。