12 Replies - 9514 Views - Last Post: 09 September 2010 - 03:03 AM Rate Topic: -----

#1 MarmiteX1  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 159
  • Joined: 17-October 09

Asynchronous TCP Client problem

Posted 22 February 2010 - 04:20 PM

Hi,

I am new to Socket programming and I am currently working through examples.

I have been looking into threads regarding Asynchronous mode of operation. I have created a TCP Client and TCP Server which runs in Asynchronously.

The problem I am facing is that the code throws an unhandled exception when i run the Client on a PDA device and Server on another PDA device. The exception is thrown in the client app.

//Client side connected 
void makeConnection(IAsyncResult iar)
        {
            client = (Socket)iar.AsyncState;
            try
            {
                client.EndConnect(iar);
                connectionStatus.Text = "Connected to:" + client.RemoteEndPoint.ToString();
                client.BeginReceive(data, 0, size, SocketFlags.None, new AsyncCallback(ReceiveData), client);
            }
            catch (Exception ex)
            {
                conStatus.Text = "Error in connecting";
            }
        }



Correct me if i am wrong but i think this may be due to the fact the the code is trying to update a control outside of the Asynchronous thread?

I would like to use a thread and delegate so that i could loop out of the makeConnection method which will handle the connectionStatus.Text and I would like to use a Control.Invoke method to handle the exception. Is this a sensible approach? How would i go about doing this? I would greatly appreciate your assistance.

Thanks

This post has been edited by MarmiteX1: 22 February 2010 - 04:21 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Asynchronous TCP Client problem

#2 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1642
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Re: Asynchronous TCP Client problem

Posted 22 February 2010 - 04:26 PM

What's the exact error message you're getting?
Was This Post Helpful? 0
  • +
  • -

#3 prajayshetty  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 31
  • View blog
  • Posts: 920
  • Joined: 27-April 07

Re: Asynchronous TCP Client problem

Posted 22 February 2010 - 07:00 PM

can u show me the entire code please so that i can get where the error is
Was This Post Helpful? 0
  • +
  • -

#4 MarmiteX1  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 159
  • Joined: 17-October 09

Re: Asynchronous TCP Client problem

Posted 24 February 2010 - 03:23 PM

View Postprajayshetty, on 22 February 2010 - 05:00 PM, said:

can u show me the entire code please so that i can get where the error is


Sorry for the delay,

Here is the code on the client side:

public partial class Client : Form
    {
        private Socket client;
        private byte[] data = new byte[1024];
        private int size = 1024;
        
        public Client()
        {
            InitializeComponent();
        }

        private void send_Click(object sender, EventArgs e)
        {
            byte[] message = Encoding.ASCII.GetBytes(newText.Text);
            newText.Text = "";
            client.BeginSend(message, 0, message.Length, SocketFlags.None,
            new AsyncCallback(SendData),client);
        }

        private void connect_Click(object sender, EventArgs e)
        {
            conStatus.Text = "Connecting...";
            Socket newSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"),9050);
            newSock.BeginConnect(iep,new AsyncCallback(Connected),newSock);
        }

        private void disconnect_Click(object sender, EventArgs e)
        {
            client.Close();
            conStatus.Text = "Disconnected";
        }

        void MakeConnection(IAsyncResult iar)
        {
            client = (Socket)iar.AsyncState;
            try
            {
                client.EndConnect(iar);
                //code fails here
                conStatus.Text = "Connected to:" + client.RemoteEndPoint.ToString();
                client.BeginReceive(data, 0, size, SocketFlags.None, new AsyncCallback(ReceiveData), client);
            }
            catch (Exception ex)
            {
                conStatus.Text = "Error connecting";
            }
        }

        void ReceiveData(IAsyncResult iar)
        {
            Socket remote = (Socket)iar.AsyncState;
            int recv = remote.EndReceive(iar);
            string stringData = Encoding.ASCII.GetString(data, 0, recv);
            results.Items.Add(stringData);
        }

        void SendData(IAsyncResult iar)
        {
            Socket remote = (Socket)iar.AsyncState;
            int sent = remote.EndSend(iar);
            remote.BeginReceive(data, 0, size, SocketFlags.None,
            new AsyncCallback(ReceiveData), remote);
        }

        
    }




Server side code i developed.
public partial class Server : Form
    {
        byte[] data = new byte[1024];
        private Socket server;

        public Server()
        {
            InitializeComponent();
            server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
            server.Bind(iep);
            server.Listen(5);
            server.BeginAccept(new AsyncCallback(AcceptConn), server);
        }

        private void Close_Click(object sender, EventArgs e)
        {
            Close();
        }

        void AcceptConn(IAsyncResult iar)
        {
            Socket oldserver = (Socket)iar.AsyncState;
            Socket client = oldserver.EndAccept(iar);
            conStatus.Text = "Connected to: " + client.RemoteEndPoint.ToString();
            string stringData = "This is my server";
            byte[] message1 = Encoding.ASCII.GetBytes(stringData);
            client.BeginSend(message1, 0, message1.Length, SocketFlags.None, new AsyncCallback(SendData), client);

        }

        void SendData(IAsyncResult iar)
        {
            Socket client = (Socket)iar.AsyncState;
            int sent = client.EndSend(iar);
            client.BeginReceive(data, 0, 1024, SocketFlags.None, new AsyncCallback(ReceiveData), client);
        }

        void ReceiveData(IAsyncResult iar)
        {
            Socket client = (Socket)iar.AsyncState;
            int recv = client.EndReceive(iar);
            if (recv == 0)
            {
                client.Close();
                conStatus.Text = "Waiting for client...";
                server.BeginAccept(new AsyncCallback(AcceptConn), server);
                return;
            }
            string receivedData = Encoding.ASCII.GetString(data, 0, recv);
            results.Items.Add(receivedData);
            byte[] message2 = Encoding.ASCII.GetBytes(receivedData);
            client.BeginSend(message2, 0, message2.Length, SocketFlags.None, new AsyncCallback(SendData), client);
        }
    }


Was This Post Helpful? 0
  • +
  • -

#5 danny_kay1710  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 29
  • View blog
  • Posts: 359
  • Joined: 27-April 08

Re: Asynchronous TCP Client problem

Posted 25 February 2010 - 01:49 AM

In your client code the IP address you try to connect to is 127.0.0.1.

This will probably throw an exception along the lines of the Remote Host rejected the connection. Is this what you are getting?

Change the IP address in the connect button click event to the IP address of the other device you wish to connect to and it should work OK (firewalls permitting of course!). May I suggest a text box to type the remote IP in that you wish to connect to before hitting connect?
Was This Post Helpful? 0
  • +
  • -

#6 MentalFloss  Icon User is offline

  • "ADDICTED"[2:5]
  • member icon

Reputation: 528
  • View blog
  • Posts: 1,397
  • Joined: 02-September 09

Re: Asynchronous TCP Client problem

Posted 25 February 2010 - 09:57 AM

This is a cross thread exception isn't it?

It'd be caused by this and other areas where you update form code in the asynchronous methods.

connectionStatus.Text = "Connected to:" + client.RemoteEndPoint.ToString();



Asynchronous methods are operating on a separate thread from your windows code. The control is on the windows thread and the method calling back to it is on a different thread. What you have to do with asynchronous methods is pack whatever you want to get out of it into the IAsynchResult and then the windows code will inspect it and perform whatever logic required. This way they stay on their own threads.

Take a look at this link: http://msdn.microsof...asyncstate.aspx

It will explain to you how to manage the state of the asynchronous operations.
Was This Post Helpful? 0
  • +
  • -

#7 MarmiteX1  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 159
  • Joined: 17-October 09

Re: Asynchronous TCP Client problem

Posted 25 February 2010 - 10:22 AM

View PostMentalFloss, on 25 February 2010 - 08:57 AM, said:

This is a cross thread exception isn't it?

It'd be caused by this and other areas where you update form code in the asynchronous methods.

connectionStatus.Text = "Connected to:" + client.RemoteEndPoint.ToString();



Asynchronous methods are operating on a separate thread from your windows code. The control is on the windows thread and the method calling back to it is on a different thread. What you have to do with asynchronous methods is pack whatever you want to get out of it into the IAsynchResult and then the windows code will inspect it and perform whatever logic required. This way they stay on their own threads.

Take a look at this link: http://msdn.microsof...asyncstate.aspx

It will explain to you how to manage the state of the asynchronous operations.



Yes, thats the problem i am having. Sure i will look into this because i dont know much about it so it should give me a good insight.

Thanks
Was This Post Helpful? 0
  • +
  • -

#8 MarmiteX1  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 159
  • Joined: 17-October 09

Re: Asynchronous TCP Client problem

Posted 28 February 2010 - 12:16 PM

View PostMentalFloss, on 25 February 2010 - 08:57 AM, said:

This is a cross thread exception isn't it?

It'd be caused by this and other areas where you update form code in the asynchronous methods.

connectionStatus.Text = "Connected to:" + client.RemoteEndPoint.ToString();



Asynchronous methods are operating on a separate thread from your windows code. The control is on the windows thread and the method calling back to it is on a different thread. What you have to do with asynchronous methods is pack whatever you want to get out of it into the IAsynchResult and then the windows code will inspect it and perform whatever logic required. This way they stay on their own threads.

Take a look at this link: http://msdn.microsof...asyncstate.aspx

It will explain to you how to manage the state of the asynchronous operations.


Hi,

I tried to set up a delegate to update the textbox status on the client app and the server app.

But an exception still keeps being thrown which says:

Quote

Control.invoke must be used to interact with controls created on a separate thread


Here is what i have done on the client side:
//set up delegate to update the status
private delegate void viewStatus(string stat);

void MakeConnection(IAsyncResult iar)
        {
            client = (Socket)iar.AsyncState;
            try
            {
                client.EndConnect(iar);
                //Added this line
                this.Invoke(new viewStatus(setValue),"Connected");
                client.BeginReceive(data, 0, size, SocketFlags.None, new AsyncCallback(ReceiveData), client);
            }
            catch (Exception ex)
            {
                Console.Writeline(ex.message.ToString());
            }
        }

 //call this method to set the value
        public void setValue(string value)
        {
            connnectionStatus.Text = value + client.RemoteEndPoint.ToString();
        }


Now in the Server i did the following:

public delegate void TheConnStatus(string stat, Socket sock);

 void AcceptConn(IAsyncResult iar)
        {
            Socket oldserver = (Socket)iar.AsyncState;
            Socket client = oldserver.EndAccept(iar);
            ////added this line
            this.Invoke(new TheConnStatus(currStatus),"connected", client));
            string stringData = "This is my server";
            byte[] message1 = Encoding.ASCII.GetBytes(stringData);
            client.BeginSend(message1, 0, message1.Length, SocketFlags.None, new AsyncCallback(SendData), client);

        }

public void currStatus(string stat, Socket sock)
{
  connectionStatus.Text = stat + sock.RemoteEndPoint.ToString();

}



So I thought the would do the trick but then an exception was thrown on the following method
 void ReceiveData(IAsyncResult iar)
        {
            Socket remote = (Socket)iar.AsyncState;
            int recv = remote.EndReceive(iar);
            string stringData = Encoding.ASCII.GetString(data, 0, recv);
            results.Items.Add(stringData);
        }



i would appreciate if you someone could assist me with the the above problem please?

Thanks
Was This Post Helpful? 0
  • +
  • -

#9 MentalFloss  Icon User is offline

  • "ADDICTED"[2:5]
  • member icon

Reputation: 528
  • View blog
  • Posts: 1,397
  • Joined: 02-September 09

Re: Asynchronous TCP Client problem

Posted 28 February 2010 - 12:48 PM

Quote

results.Items.Add(stringData);



You're still cross-thread accessing controls. You have to get the stringData out of this method, and back on the original thread, you add the stringData to the results object.
Was This Post Helpful? 0
  • +
  • -

#10 MarmiteX1  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 159
  • Joined: 17-October 09

Re: Asynchronous TCP Client problem

Posted 15 March 2010 - 03:55 PM

Hi,

Thanks, i have solved it.

I am also trying to send the data from the server back to the client but i keep getting the following error message:

Quote

A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied


Here is the code i am using:

public delegate void TheConnStatus(string stat, Socket sock, string data);

private void Send_Click(object sender, EventArgs e)
{
byte[] myMessage = Encoding.ASCII.GetBytes(ServerTextBox.Text);
this.Invoke(new TheConnStatus(currStatus), "Sent:",server,Textbox1.Text);
server.BeginSend(myMessage, 0, myMessage.Length, SocketFlags.None,new AsyncCallback(SendData), server);
}

public void currStatus(string stat, Socket sock, string data)
{
  connectionStatus.Text = stat + sock.RemoteEndPoint.ToString();
  results.Items.Add(receivedData);
}



I delcared the "Socket server" globally and i bind the socket to the IP in the construtor as you can see in my intial post.

I would appreciate if somebody could assist me with this please?

Thanks,
Was This Post Helpful? 0
  • +
  • -

#11 prajayshetty  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 31
  • View blog
  • Posts: 920
  • Joined: 27-April 07

Re: Asynchronous TCP Client problem

Posted 15 March 2010 - 04:18 PM

this error normally happens if u have closed the connection on the server side or the client has closed the connnection it ,occurred with me too when i was writting the asynchronous code and ya do use manureset event, in your code this will help you use it like this

use ManualResetevent check msdn for that that is the reason for this error and one more question u getting the execption on the server side or on the client side i used to get this error but then used manualreset event it fixed it up and i guess it should be
 client.BeginSend(myMessage, 0, myMessage.Length, SocketFlags.None,new AsyncCallback(SendData), server);


rather then
server.BeginSend(myMessage, 0, myMessage.Length, SocketFlags.None,new AsyncCallback(SendData), server);


This post has been edited by prajayshetty: 15 March 2010 - 04:32 PM

Was This Post Helpful? 0
  • +
  • -

#12 MarmiteX1  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 159
  • Joined: 17-October 09

Re: Asynchronous TCP Client problem

Posted 19 March 2010 - 12:54 PM

Hi,

I am getting the error on the Server side.

The error occurs on the Invoke method.

Please could you assist me further with this.

Thanks,
Was This Post Helpful? 0
  • +
  • -

#13 Nick1979  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 09-September 10

Re: Asynchronous TCP Client problem

Posted 09 September 2010 - 03:03 AM

Use .Net Protocol Builder to generate the code for the entire protocol, this tool can generate the code for packets, client/server connections and for the listener in the server side ... all of them work in asynchronous fashion, I have used it 3 months ago, it really save my time going through all of the headache because of the cross threading .. and raw data used in the NetworkStream ... see http://www.protocol-builder.com/
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1