StreamReader-套接字中的ReadLine没有';t停止

本文关键字:停止 没有 套接字 ReadLine StreamReader- | 更新日期: 2023-09-27 18:00:02

我正在尝试与服务器通信。

这是我的简单代码:

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或其他内容。

有人能向我解释一下,从服务器上获取所有线路并继续前进的最佳做法是什么吗?

StreamReader-套接字中的ReadLine没有';t停止

我这样解决了它:

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已经说过的,溪流不知道什么时候结束。只要您正在与服务器通信,就可以等待响应。

我把监听服务器的代码放在后台工作程序中,当出现新响应时,它总是监听并发送事件。