Search code examples
c#socketsexceptiontcpclient

Reading from clientsocket: ArgumentOutOfRangeException was unhandled


I was using this tutorial to see how it works: http://csharp.net-informations.com/communications/csharp-chat-server-programming.htm

(http://csharp.net-informations.com/communications/csharp-chat-client.htm)

This is what I've done:

  • Downloaded the code
  • Started two Visual Studio Instances : One for the Client Side, One for the Server Side.

  • Ran the Server : Server running fine

  • Ran Client Side, entered name in textbox, pressed connect button and this is what i get on this line in the Server Program :

    networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
    

ArgumentOutOfRangeException was unhandled.

I did not change the original code. Funny is that the same code I've downloaded two years ago and it worked fine (was on Windows 7, now I'm on Windows 10).


Solution

  • The bytesFrom is 10025 bytes long. The clientSocket.ReceiveBufferSize in theory may become longer than this size (probably due to Window Auto-Tuning feature). To fix the issue initialize your buffer with clientSocket.ReceiveBufferSize:

    byte[] bytesFrom = new byte[clientSocket.ReceiveBufferSize];
    

    Note also that in the client code you've got a similar issue in getMessage(). There you should also change buffer initialization code:

    buffSize = clientSocket.ReceiveBufferSize;
    byte[] inStream = new byte[buffSize];
    serverStream.Read(inStream, 0, buffSize);