Jerad Hobgood
Jerad Hobgood

Reputation: 39

C# Server program throwing exception

I have successfully connected my Client program to my server, however when trying to do basic write to server I am getting error

System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)

Here is my code excluding the connection and stopping the connection

while ((true)) {
    try {
        requestCount = requestCount + 1;
        NetworkStream networkStream = clientSocket.GetStream();
        byte[] bytesFrom = new byte[10025];

        //Problem
        networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
        string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
        dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));

        Console.WriteLine(" >> Data from client - " + dataFromClient);
        string serverResponse = "Last Message from client" + dataFromClient;

        Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
        networkStream.Write(sendBytes, 0, sendBytes.Length);
        networkStream.Flush();
        Console.WriteLine(" >> " + serverResponse);
    }
    catch (Exception ex) {
        Console.WriteLine(ex.ToString());
    }
}

Upvotes: 2

Views: 103

Answers (1)

Nico
Nico

Reputation: 3542

You are reading beyond the size of the supplied buffer, try:

networkStream.Read(bytesFrom, 0, bytesFrom.Length);

Upvotes: 3

Related Questions