9 Replies - 2158 Views - Last Post: 19 June 2013 - 10:45 AM Rate Topic: -----

#1 optix212  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 27
  • View blog
  • Posts: 509
  • Joined: 10-October 09

Specified argument was out of range of valid values

Posted 18 June 2013 - 01:34 PM

I am trying to make a simple Client/Server chat application that is heavily based off of this one: http://csharp.net-in...programming.htm

My problem is that both the client and the server throw exceptions at me at the lines commented below. As I have NO experience with TCP, Buffers, or ByteArrays, I am at quite a loss here on how to fix this issue.. I have tried replacing byte[] inStream = new byte[1024]; with all sorts of numbers, but to no avail.. Can anyone please elaborate what is going wrong here? The exception reads as follows:

Quote

Specified argument was out of the range of valid values.




Client Side:
        private void getMessage()
        {
            while (true)
            {
                serverStream = clientSocket.GetStream();
                int buffSize = 0;
                byte[] inStream = new byte[1024];
                buffSize = clientSocket.ReceiveBufferSize;
                serverStream.Read(inStream, 0, buffSize); //Exception comes from this line
                string returndata = System.Text.Encoding.ASCII.GetString(inStream);
                readData = "" + returndata;
                msg();
            }
        }



Server Side:
        static void Main(string[] args)
        {
            TcpListener serverSocket = new TcpListener(8888);
            TcpClient clientSocket = default(TcpClient);
            int counter = 0;

            serverSocket.Start();
            Console.WriteLine ("Chat Server Started ....");
            counter = 0;
            while ((true))
            {
                counter += 1;
                clientSocket = serverSocket.AcceptTcpClient();

                byte[] bytesFrom = new byte[1024];
                string dataFromClient = null;

                NetworkStream networkStream = clientSocket.GetStream();
                networkStream.Read(bytesFrom, 0, clientSocket.ReceiveBufferSize);  //Exception comes from this line
                dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));

                clientsList.Add(dataFromClient, clientSocket);

                broadcast(dataFromClient + " Joined ", dataFromClient, false);

                Console.WriteLine(dataFromClient + " Joined chat room ");
                handleClinet client = new handleClinet();
                client.startClient(clientSocket, dataFromClient, clientsList);
            }

            clientSocket.Close();
            serverSocket.Stop();
            Console.WriteLine("exit");
            Console.ReadLine();
        }



Is This A Good Question/Topic? 0
  • +

Replies To: Specified argument was out of range of valid values

#2 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2263
  • View blog
  • Posts: 9,468
  • Joined: 29-May 08

Re: Specified argument was out of range of valid values

Posted 18 June 2013 - 01:40 PM

Have you referred back to the documentation on MSDN (link) to see want the valid argument ranges are for the parameters.
Was This Post Helpful? 0
  • +
  • -

#3 optix212  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 27
  • View blog
  • Posts: 509
  • Joined: 10-October 09

Re: Specified argument was out of range of valid values

Posted 18 June 2013 - 01:45 PM

I have.. It tells me to use bytesFrom.Length instead of clientSocket.ReceiveBufferSize, but it throws the same exception....

I have.. It tells me to use bytesFrom.Length instead of clientSocket.ReceiveBufferSize, but it throws the same exception....
Was This Post Helpful? 0
  • +
  • -

#4 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5535
  • View blog
  • Posts: 11,857
  • Joined: 02-June 10

Re: Specified argument was out of range of valid values

Posted 18 June 2013 - 02:49 PM

Forgive my bias, but I think the tutorials for doing client/server/chat here on DIC are better tutorials.

FAQ 10


tlhIn`toq's FAQ list


TOP most asked:
What does this error message mean?
FAQ 2: How do I debug
FAQ 3: How do I make Class1/Form1 talk to Class2/Form2


FAQ (Frequently Asked Questions - Updated Apr 2013
Spoiler



This post has been edited by tlhIn`toq: 18 June 2013 - 02:50 PM

Was This Post Helpful? 0
  • +
  • -

#5 optix212  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 27
  • View blog
  • Posts: 509
  • Joined: 10-October 09

Re: Specified argument was out of range of valid values

Posted 19 June 2013 - 06:21 AM

As I do like the chat tutorials on this forum, they are a bit too much for the program I am trying to make. All I want is a chatroom where everyone can mass connect and all chat together. I have been scratching my head at this for two days now, and still haven't gotten anywhere.. I know it has to be something simple..
Was This Post Helpful? 0
  • +
  • -

#6 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5535
  • View blog
  • Posts: 11,857
  • Joined: 02-June 10

Re: Specified argument was out of range of valid values

Posted 19 June 2013 - 06:39 AM

Quote

09        serverStream.Read(inStream, 0, buffSize); //Exception comes from this line


Please recreate the error, then post a screen shot showing the run-time values of inStream and buffSize (The Locals pallet for example)
Was This Post Helpful? 0
  • +
  • -

#7 optix212  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 27
  • View blog
  • Posts: 509
  • Joined: 10-October 09

Re: Specified argument was out of range of valid values

Posted 19 June 2013 - 08:44 AM

This is what the server is returning:

Posted Image

It's weird because it says that bytesFrom[] has a length of 10025.. It SHOULD be 65536. I don't understand that at all.

Here is what the Client is returning:

Posted Image

My outStream[] has a length of 8, so I don't know how it is returning a length of 10025 to bytesFrom[]. I am at a loss here?

Here is the full code for the client:
using System;
using System.Windows.Forms;
using System.Text;
using System.Net.Sockets;
using System.Threading;

namespace Project_Management
{
    public partial class Chat : Form
    {
        System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
        NetworkStream serverStream = default(NetworkStream);
        string readData = null;

        public Chat()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            readData = "Conected to Chat Server ...";
            msg();
            clientSocket.Connect("127.0.0.1", 8888);
            serverStream = clientSocket.GetStream();
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes(nameTextBox.Text + "$");
            string myOut = System.Text.Encoding.ASCII.GetString(outStream);
            MessageBox.Show(outStream.Length.ToString() + "\n" + myOut );
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();

            Thread ctThread = new Thread(getMessage);
            ctThread.Start();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes(readTextBox.Text + "$");
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();
        }

        private void getMessage()
        {
            try
            {
                while (true)
                {
                    serverStream = clientSocket.GetStream();
                    int buffSize = 0;
                    byte[] inStream = new byte[65537];
                    buffSize = clientSocket.ReceiveBufferSize;
                    MessageBox.Show("Size: " + buffSize.ToString() + "\n" + "Buffer: " + inStream.Length);
                    serverStream.Read(inStream, 0, buffSize);
                    string returndata = System.Text.Encoding.ASCII.GetString(inStream);
                    readData = "" + returndata;
                    msg();
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }

        private void msg()
        {
            if (this.InvokeRequired)
                this.Invoke(new MethodInvoker(msg));
            else
                readTextBox.Text = readTextBox.Text + Environment.NewLine + " >> " + readData;
        } 
    }
}





Here is the full code for the server:

using System;
using System.Threading;
using System.Net.Sockets;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        public static Hashtable clientsList = new Hashtable(); 

        static void Main(string[] args)
        {
            try
            {
                TcpListener serverSocket = new TcpListener(8888);
                TcpClient clientSocket = default(TcpClient);
                int counter = 0;

                serverSocket.Start();
                Console.WriteLine("Chat Server Started ....");
                counter = 0;
                while ((true))
                {
                    try
                    {
                        counter += 1;
                        clientSocket = serverSocket.AcceptTcpClient();


                        byte[] bytesFrom = new byte[65537];
                        string dataFromClient = null;

                        NetworkStream networkStream = clientSocket.GetStream();
                        Console.WriteLine("BytesFrom: " + bytesFrom.ToString() + "\n" + "Size: " + clientSocket.ReceiveBufferSize.ToString());
                        if (clientSocket.Connected == true)
                        {
                            networkStream.Read(bytesFrom, 0, bytesFrom.Length);
                        }
                        else
                        {
                            Console.WriteLine("Socket not connected");
                        }
                        dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                        dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));

                        clientsList.Add(dataFromClient, clientSocket);

                        broadcast(dataFromClient + " Joined ", dataFromClient, false);

                        Console.WriteLine(dataFromClient + " Joined chat room ");
                        handleClinet client = new handleClinet();
                        client.startClient(clientSocket, dataFromClient, clientsList);
                    }
                    catch(Exception exc)
                    {
                        Console.WriteLine(exc.Message);
                    }

                }

                clientSocket.Close();
                serverSocket.Stop();
                Console.WriteLine("exit");
                Console.ReadLine();
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.InnerException.Message);
            }
        }

        public static  void broadcast(string msg, string uName, bool flag)
        {
            try
            {
                foreach (DictionaryEntry Item in clientsList)
                {
                    TcpClient broadcastSocket;
                    broadcastSocket = (TcpClient)Item.Value;
                    NetworkStream broadcastStream = broadcastSocket.GetStream();
                    byte[] broadcastBytes = null;

                    if (flag == true)
                    {
                        broadcastBytes = Encoding.ASCII.GetBytes(uName + " says : " + msg);
                    }
                    else
                    {
                        broadcastBytes = Encoding.ASCII.GetBytes(msg);
                    }

                    broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length);
                    broadcastStream.Flush();
                }
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
            }
        }  //end broadcast function
    }//end Main class


    public class handleClinet
    {
        TcpClient clientSocket;
        string clNo;
        Hashtable clientsList;

        public void startClient(TcpClient inClientSocket, string clineNo, Hashtable cList)
        {
            this.clientSocket = inClientSocket;
            this.clNo = clineNo;
            this.clientsList = cList;
            Thread ctThread = new Thread(doChat);
            ctThread.Start();
        }

        private void doChat()
        {
            int requestCount = 0;
            byte[] bytesFrom = new byte[65537];
            string dataFromClient = null;
            Byte[] sendBytes = null;
            string serverResponse = null;
            string rCount = null;
            requestCount = 0;

            while ((true))
            {
                try
                {
                    requestCount = requestCount + 1;
                    NetworkStream networkStream = clientSocket.GetStream();
                    networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
                    dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                    dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
                    Console.WriteLine("From client - " + clNo + " : " + dataFromClient);
                    rCount = Convert.ToString(requestCount);

                    Program.broadcast (dataFromClient, clNo, true);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }//end while
        }//end doChat
    } //end class handleClinet
}//end namespace


This post has been edited by optix212: 19 June 2013 - 08:49 AM

Was This Post Helpful? 0
  • +
  • -

#8 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5535
  • View blog
  • Posts: 11,857
  • Joined: 02-June 10

Re: Specified argument was out of range of valid values

Posted 19 June 2013 - 09:03 AM

Sure does explain the error though, doesn't it?
Argument out of range when you have an array initialized to 1024 and data size of 10025.

Without studying the code my first thought/test is the data might be coming from an unexpected source. Try changing ports. Maybe you are using a port that another application is also using so your app is trying to make sense of data from... Anti-virus update, or Windows Update, or iTunes streaming music.

Otherwise this really comes down to basic (and tedious) debugging. You start with a known problem: The size of the array. Then work backwards to see where that is assigned and what does all that data contain and therefore point you towards. Then where does that come from. Then where does that come from.

FAQ 2 from post 4 above links to several tutorials on debugging. Sometimes taking a break from the project to invest a couple hours in your debugging skillset is the fastest direction to take.
Was This Post Helpful? 1
  • +
  • -

#9 optix212  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 27
  • View blog
  • Posts: 509
  • Joined: 10-October 09

Re: Specified argument was out of range of valid values

Posted 19 June 2013 - 10:11 AM

It definitely does explain the error... 10025 was the value that bytesFrom[] was originally assigned, but then I changed it to 65536 because that's what the client is pushing.. I have looked through the code a lot, and debugged as much as I know how and still... I don't see where 10025 is coming from....

Also, when I open it in the Locals window, it says that every value in the array is 0. If there were some other conflicting software, wouldn't it still read pieces of data in the array? Also, should I forward a port on my router in order for this to work? I believe the server is opening it for me, but I'm just making sure.
Was This Post Helpful? 0
  • +
  • -

#10 optix212  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 27
  • View blog
  • Posts: 509
  • Joined: 10-October 09

Re: Specified argument was out of range of valid values

Posted 19 June 2013 - 10:45 AM

I figured it out! For some reason the server application was compiling from another source.. Every time I would update it, it would update the project somewhere else, and every time I would build it, it would start the program with its original code. I got it to connect, though.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1