从流中读

时间:2014-05-08 14:06:43

标签: c# .net tcpclient networkstream

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

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();并且不起作用。与服务器的连接很好并且正常工作,因为服务器写了我的客户端应用程序正在访问连接的消息。

1 个答案:

答案 0 :(得分:0)

您的阅读方法不安全。这是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