Question

C# asynchronous socket client

Asked by: dspradling

I am trying to understand and develop a client that can communicate with a hardware system over TCP/IP.  I found an article on a basic client here (http://www.java2s.com/Code/CSharp/Network/AsyncTcpClient.htm) and modified the code slightly to test with.  I can connect to the hardware and return a response to verify that it is communicating but when I send a command it does not respond and throws an ObjectDisposedException in ReceiveData block when the disconnect button is clicked.    I assume it is waiting for the hardware to return data but I'm not sure why it isn't receiving.   I am able to connect and send commands with a simple console app.

using System;
using System.Drawing;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
 
 
public class AsyncTcpClient : Form
{
    private TextBox newText;
    private TextBox conStatus;
    private ListBox results;
    private Socket client;
    private byte[] data = new byte[1024];
    private int size = 1024;
 
    public AsyncTcpClient()
    {
        Text = "Asynchronous TCP Client";
        Size = new Size(400, 380);
 
        Label label1 = new Label();
        label1.Parent = this;
        label1.Text = "Enter text string:";
        label1.AutoSize = true;
        label1.Location = new Point(10, 30);
 
        newText = new TextBox();
        newText.Parent = this;
        newText.Size = new Size(200, 2 * Font.Height);
        newText.Location = new Point(10, 55);
 
        results = new ListBox();
        results.Parent = this;
        results.Location = new Point(10, 85);
        results.Size = new Size(360, 18 * Font.Height);
 
        Label label2 = new Label();
        label2.Parent = this;
        label2.Text = "Connection Status:";
        label2.AutoSize = true;
        label2.Location = new Point(10, 330);
 
        conStatus = new TextBox();
        conStatus.Parent = this;
        conStatus.Text = "Disconnected";
        conStatus.Size = new Size(200, 2 * Font.Height);
        conStatus.Location = new Point(110, 325);
 
        Button sendit = new Button();
        sendit.Parent = this;
        sendit.Text = "Send";
        sendit.Location = new Point(220, 52);
        sendit.Size = new Size(5 * Font.Height, 2 * Font.Height);
        sendit.Click += new EventHandler(ButtonSendOnClick);
 
        Button connect = new Button();
        connect.Parent = this;
        connect.Text = "Connect";
        connect.Location = new Point(295, 20);
        connect.Size = new Size(6 * Font.Height, 2 * Font.Height);
        connect.Click += new EventHandler(ButtonConnectOnClick);
 
        Button discon = new Button();
        discon.Parent = this;
        discon.Text = "Disconnect";
        discon.Location = new Point(295, 52);
        discon.Size = new Size(6 * Font.Height, 2 * Font.Height);
        discon.Click += new EventHandler(ButtonDisconOnClick);
    }
 
    void ButtonConnectOnClick(object obj, EventArgs ea)
    {
        conStatus.Text = "Connecting...";
        Socket newsock = new Socket(AddressFamily.InterNetwork,
                              SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint iep = new IPEndPoint(IPAddress.Parse("10.5.48.225"), 4000);
        newsock.BeginConnect(iep, new AsyncCallback(Connected), newsock);
    }
 
    void ButtonSendOnClick(object obj, EventArgs ea)
    {
        byte[] message = Encoding.ASCII.GetBytes(newText.Text);
        client.BeginSend(message, 0, message.Length, SocketFlags.None, new AsyncCallback(SendData), client);
        newText.Clear();
    }
 
    void ButtonDisconOnClick(object obj, EventArgs ea)
    {
        client.Close();
        conStatus.Text = "Disconnected";
    }
 
    void Connected(IAsyncResult iar)
    {
        client = (Socket)iar.AsyncState;
        try
        {
            this.BeginInvoke(
                (MethodInvoker)delegate()
                {
                    client.EndConnect(iar);
                    conStatus.Text = "Connected to: " + client.RemoteEndPoint.ToString();
                    client.BeginReceive(data, 0, size, SocketFlags.None,
                                  new AsyncCallback(ReceiveData), client);
                });
        }
        catch (SocketException)
        {
            conStatus.Text = "Error connecting";
        }
    }
 
    void ReceiveData(IAsyncResult iar)
    {
        this.BeginInvoke(
            (MethodInvoker)delegate()
            {
                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);
    }
 
    public static void Main()
    {
        Application.Run(new AsyncTcpClient());
    }
}

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-05-21 at 13:41:29ID24429203
Tags

C#

Topic

C# Programming Language

Participating Experts
1
Points
0
Comments
3

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Asynchronous socket programming (Proxy server)
    I'm currently involved in writing kind of a forwarding HTTP proxy server. I decided to base on a existing code from www.mentalis.org. I modified it slightly to work as follows: it listens on a specified port and all requests are forwarded to a www server on the same machine (...
  2. Asynchronous Socket callback help please
    I have a C# application using Asynchronous sockets. I am using Telnet on the 'remote' end to test connections, here is my callback procedure in C#: public static void AcceptCallback(IAsyncResult ar) { try{ Server server = (Server)ar.AsyncState; Socket client = server.li...
  3. How can I know of network failure when using asynchrono…
    Im writing up a time server which connects with clients asynchronously. I am able to pick up the socket exceptions thrown when client disconnects remotely/by force but when i pull the client network cable out (i.e. event of network failure) how can i kno that the particular c...
  4. Asynchronous Sockets Implementation
    Looking for a Thread-Safe Asynchronous Sockets Implementation i can use to modify & learn with. A console app is fine as id like to connect using telnet or similar to do testing and see how it all works. Nothing fancy, just the basics behind it. Thanks Jaz
  5. Asynchronous Socket Error 10053 Handling - Delphi …
    Hi all, Having a few problems trapping 'Asynchronous Socket Error 10053' in my application - written in delphi 2005, using TCP ClientSocket and ServerSocket. I have tried placing the 'Errorcode := 0;' within ClientSocketError and also 'Try,Except', however i still get the b...
  6. Sleep mode and asynchronous socket Error
    Hi Experts, Hope this question finds you well. I have a multi tier application that I have developed. When the client machine hibernates or goes into sleep mode, an a asynchronous socket error occurs on the server. I get an error message on the server which locls up t...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: jensfiedererPosted on 2009-05-22 at 10:48:39ID: 24453450

Not sure exactly what you are saying here, you are a bit indefinite with your "it" and "I".....if the client can send a message and receive a response from the hardware (obviously I have no access to your hardware!) it sounds like you are doing well.

"I can connect" = your client connects?
"return a response" = your hardware responds to your client?  did your client send a command yet?  to what is it responding?
"I send a command" = you click the send button?
"it does not respond" = ?

 

by: dspradlingPosted on 2009-05-24 at 15:56:36ID: 24463387

The client can connect to the hardware and does receive a response from the hardware stating that it is connected.  I then attempt to send a command to the hardware and expect a response.  I can verify the hardware is working correctly because I can telnet into the hardware server and it behaves normally.  The client does not behave as expected when a command is sent via the TCP client.  The client stops responding when a command is sent.  I have also tried to use this client to connect to a SMTP server and it behaves in a similar manner, meaning I can connect and receive a 220 response from the mail server but when I send a HELO command the client becomes unresponsive.  No exception is thrown.

"I can connect" = your client connects? --yes it connects

"return a response" = your hardware responds to your client? -- yes it responds with 1Connected to Eagle Test System 10.5.48.225 upon connection  (the response is received in the client)

did your client send a command yet?   to what is it responding? --I type the command A in the textbox and click the Send button.  The response should be ACK-Print Complete Enabled as verified via telnet

"I send a command" = you click the send button? --yes

"it does not respond" = ? --No

You could try and reproduce the results I am seeing against a mail server or other telnet service.

 

by: dspradlingPosted on 2009-05-25 at 10:53:12ID: 24467772

Added note.  I found this code on MSDN on an Asynchronous Client Socket Example.  This code hangs on the socket response as well.  I don't get it.  I don't understand what is going wrong here.

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
 
// State object for receiving data from remote device.
public class StateObject
{
    // Client socket.
    public Socket workSocket = null;
    // Size of receive buffer.
    public const int BufferSize = 256;
    // Receive buffer.
    public byte[] buffer = new byte[BufferSize];
    // Received data string.
    public StringBuilder sb = new StringBuilder();
}
 
public class AsynchronousClient
{
 
    // ManualResetEvent instances signal completion.
    private static ManualResetEvent connectDone = new ManualResetEvent(false);
    private static ManualResetEvent sendDone = new ManualResetEvent(false);
    private static ManualResetEvent receiveDone = new ManualResetEvent(false);
 
    // The response from the remote device.
    private static String response = String.Empty;
 
    private static void StartClient()
    {
        // Connect to a remote device.
        try
        {
 
            int port = 25;
            IPHostEntry ipHostInfo = Dns.GetHostEntry("mail.watlow.com");
            IPAddress ipAddress = ipHostInfo.AddressList[0];
 
            //int port = 4000;
            //IPAddress ipAddress = IPAddress.Parse("10.5.48.225");
 
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
 
            // Create a TCP/IP socket.
            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 
            // Connect to the remote endpoint.
            client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
            connectDone.WaitOne();
 
            //Receive(client);
            //receiveDone.WaitOne();
            //Console.WriteLine("Response received : {0}", response);
 
            // Send test data to the remote device.
            Send(client, "HELO");
            sendDone.WaitOne();
 
            // Receive the response from the remote device.
            Receive(client);
            receiveDone.WaitOne();
 
            // Write the response to the console.
            Console.WriteLine("Response received : {0}", response);
 
            // Release the socket.
            Console.ReadLine();
            client.Shutdown(SocketShutdown.Both);
            client.Close();
 
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
 
    private static void ConnectCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the socket from the state object.
            Socket client = (Socket)ar.AsyncState;
 
            // Complete the connection.
            client.EndConnect(ar);
 
            Console.WriteLine("Socket connected to {0}", client.RemoteEndPoint.ToString());
 
            // Signal that the connection has been made.
            connectDone.Set();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
 
    private static void Receive(Socket client)
    {
        try
        {
            // Create the state object.
            StateObject state = new StateObject();
            state.workSocket = client;
            // Begin receiving the data from the remote device.
            client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
 
    private static void ReceiveCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the state object and the client socket 
            // from the asynchronous state object.
            StateObject state = (StateObject)ar.AsyncState;
            Socket client = state.workSocket;
 
            // Read data from the remote device.
            int bytesRead = client.EndReceive(ar);
            Console.WriteLine("Read data from the remote device.");
            if (bytesRead > 0)
            {
                // There might be more data, so store the data received so far.
                state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
                Console.WriteLine(state.sb);
 
                // Get the rest of the data.
                client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
                Console.WriteLine("Code hangs here");
            }
            else
            {
                // All the data has arrived; put it in response.
                if (state.sb.Length > 1)
                {
                    response = state.sb.ToString();
                }
                // Signal that all bytes have been received.
                receiveDone.Set();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
 
    private static void Send(Socket client, String data)
    {
        // Convert the string data to byte data using ASCII encoding.
        byte[] byteData = Encoding.ASCII.GetBytes(data);
 
        // Begin sending the data to the remote device.
        client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client);
    }
 
    private static void SendCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the socket from the state object.
            Socket client = (Socket)ar.AsyncState;
 
            // Complete sending the data to the remote device.
            int bytesSent = client.EndSend(ar);
            Console.WriteLine("Sent {0} bytes to server.", bytesSent);
 
            // Signal that all bytes have been sent.
            sendDone.Set();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
 
    public static int Main(String[] args)
    {
        StartClient();
        return 0;
    }
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:

Select allOpen in new window

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...