C# Socket异步通讯客户端实现源码
达拉特网站制作公司哪家好,找创新互联公司!从网页设计、网站建设、微信开发、APP开发、响应式网站等网站项目制作,到程序开发,运营维护。创新互联公司于2013年创立到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选创新互联公司。
C# Socket异步通讯客户端之主程序:
- 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 {
- // The port number for the remote device.
- private const int port = 11000;
- // 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 {// Establish the remote endpoint for the socket.
// The name of the
// remote device is "host.contoso.com".
IPHostEntry ipHostInfo = Dns.Resolve("host.contoso.com");
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);- // 生成一个TCP/IP socket.
- Socket client = new Socket(AddressFamily.InterNetwork,
- SocketType.Stream, ProtocolType.Tcp);
- // 与目标终端连接.
- client.BeginConnect(remoteEP,
- new AsyncCallback(ConnectCallback), client);
- //等待,直到连接程序完成。在ConnectCallback中适当位置有connecDone.Set()语句
- connectDone.WaitOne();
- // 发送数据到远程终端.
- Send(client, "This is a test
"); - sendDone.WaitOne();
- // 接收返回数据.
- Receive(client);
- receiveDone.WaitOne();
- // Write the response to the console.
- Console.WriteLine("Response received : {0}", response);
- // Release the socket.
- client.Shutdown(SocketShutdown.Both);
- client.Close();
- return 0;
- }
C# Socket异步通讯客户端之连接部分Callback:
- private static void ConnectCallback(IAsyncResult ar)
- {
- // 从state对象获取socket.
- Socket client = (Socket)ar.AsyncState;
- // 完成连接.
- client.EndConnect(ar);
- Console.WriteLine("Socket connected to {0}",
- client.RemoteEndPoint.ToString());
- // 连接已完成,主线程继续.
- connectDone.Set();
- } catch (Exception e) {
- Console.WriteLine(e.ToString());
- }
- }
C# Socket异步通讯客户端之数据接收:
- private static void Receive(Socket client)
- try {{
- // 构造容器state.
- StateObject state = new StateObject();
- state.workSocket = client;
- // 从远程目标接收数据.
- 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)
- {
- // 从输入参数异步state对象中获取state和socket对象
- StateObject state = (StateObject)ar.AsyncState;
- Socket client = state.workSocket;
- //从远程设备读取数据
- int bytesRead = client.EndReceive(ar);
- if (bytesRead > 0)
- {
- // 有数据,存储.
- state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
- // 继续读取.
- client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
- new AsyncCallback(ReceiveCallback), state);
- }
- else
- {
- // 所有数据读取完毕.
- if (state.sb.Length > 1)
- {
- response = state.sb.ToString();
- }
- // 所有数据读取完毕的指示信号.
- receiveDone.Set();
- }
- } catch (Exception e) {
- Console.WriteLine(e.ToString());
- }
- }
C# Socket异步通讯客户端之发送数据:
- private static void Send(Socket client, String data)
- {
- // 格式转换.
- byte[] byteData = Encoding.ASCII.GetBytes(data);
- // 开始发送数据到远程设备.
- client.BeginSend(byteData, 0, byteData.Length, 0,
- new AsyncCallback(SendCallback), client);
- }
- private static void SendCallback(IAsyncResult ar)
- {
- // 从state对象中获取socket
- Socket client = (Socket)ar.AsyncState;
- // 完成数据发送.
- int bytesSent = client.EndSend(ar);
- Console.WriteLine("Sent {0} bytes to server.", bytesSent);
- // 指示数据已经发送完成,主线程继续.
- sendDone.Set();
- }
- } catch (Exception e) {
- Console.WriteLine(e.ToString());
- }
- }
- public static int Main(String[] args) {
- StartClient();
- return 0;
- }
- }
C# Socket异步通讯客户端的实现源码内容就基本向你介绍到这里,希望对你了解和学习C# Socket异步通讯有所帮助。
文章名称:C#Socket异步通讯实现详解
标题来源:http://www.shufengxianlan.com/qtweb/news10/60960.html
网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联