1

I using this kind of code to work with some server:

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(' ');
        ...
    }
}

I've no exception, but my application stack in line with string msg = reader.ReadLine(); and doesn't work. Connection to server is good and work, because server write message that my client app was accesing connection.

Andy
  • 3,997
  • 2
  • 19
  • 39
grigorij89
  • 33
  • 6
  • 4
    Maybe the server sends a different line ending? Try using `Read()` to see what comes out. – leppie May 08 '14 at 14:09

1 Answers1

0

Your reading method is unsafe. Here is the signature of StreamReader.ReadLine method:

//
// 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();

First of all, it can (and must) return null and you'll get NullReferenceException next line.

Reading data from network is not trivial thing. Luckily, it was discussed many times:

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

Community
  • 1
  • 1
astef
  • 8,575
  • 4
  • 56
  • 95