【问题标题】:Reading from stream从流中读取
【发布时间】:2014-06-25 23:41:10
【问题描述】:

我使用这种代码来处理一些服务器:

int port = 6789;
string serverAddress = "127.0.0.1";
string playersName = "random";

TcpClient client = null;
StreamWriter writer = null;
StreamReader reader = null;             

try
{
    client = new TcpClient();
    client.Connect(serverAddress, port);                
    NetworkStream stream = client.GetStream();

    writer = new StreamWriter(stream);
    writer.Write("100 " + playersName + "\r\n");
    writer.Flush(); 

    reader = new StreamReader(stream);
    bool isRunning = true;

    while (isRunning) 
    {
        string msg = reader.ReadLine();    //stack in this line 
        string[] parts = msg.Split(' ');
        ...
    }
}

我也不例外,但我的应用程序堆栈符合string msg = reader.ReadLine(); 并且不起作用。与服务器的连接很好并且可以正常工作,因为服务器会写入我的客户端应用程序正在访问连接的消息。

【问题讨论】:

  • 也许服务器发送了不同的行尾?尝试使用Read() 看看会发生什么。

标签: c# .net tcpclient networkstream


【解决方案1】:

您的阅读方法不安全。这是StreamReader.ReadLine方法的签名:

//
// Summary:
//     Reads a line of characters from the current stream and returns the data as
//     a string.
//
// Returns:
//     The next line from the input stream, or null if the end of the input stream
//     is reached.
//
// Exceptions:
//   System.OutOfMemoryException:
//     There is insufficient memory to allocate a buffer for the returned string.
//
//   System.IO.IOException:
//     An I/O error occurs.
public override string ReadLine();

首先,它可以(并且必须)返回null,然后你会在下一行得到NullReferenceException

从网络读取数据并不是一件小事。幸运的是,它被讨论了很多次:

What is the correct way to read from NetworkStream in .NET

Ensure streamreader doesn't hang waiting for data

TCPClient not reading the incoming data

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    • 2013-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多