comparison Messaging/Client/Sockets/AsynchronousClient.cs @ 26:045dac571339

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