C# Socket异步通讯客户端之主程序:
- # public static int Main(String[] args)
- # {
- #
- # IPAddress ipAddress = IPAddress.Parse("192.168.1.104");
- # int port = 20000;
- # 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<EOF>");
- # 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:
- 1. private static void ConnectCallback(IAsyncResult ar)
- 2. {
- 3.
- 4. // 从state对象获取socket.
- 5. Socket client = (Socket)ar.AsyncState;
- 6.
- 7. // 完成连接.
- 8. client.EndConnect(ar);
- 9.
- 10. Console.WriteLine("Socket connected to {0}",
- 11. client.RemoteEndPoint.ToString());
- 12.
- 13. // 连接已完成,主线程继续.
- 14. connectDone.Set();
- 15. }
C# Socket异步通讯客户端之数据接收:
- # private static void Receive(Socket client)
- # {
- #
- # // 构造容器state.
- # StateObject state = new StateObject();
- # state.workSocket = client;
- #
- # // 从远程目标接收数据.
- # client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
- # new AsyncCallback(ReceiveCallback), state);
- #
- # }
- #
- # 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();
- # }
- #
- # }
C# Socket异步通讯客户端之发送数据:
- 1. private static void Send(Socket client, String data)
- 2. {
- 3. // 格式转换.
- 4. byte[] byteData = Encoding.ASCII.GetBytes(data);
- 5.
- 6. // 开始发送数据到远程设备.
- 7. client.BeginSend(byteData, 0, byteData.Length, 0,
- 8. new AsyncCallback(SendCallback), client);
- 9. }
- 10.
- 11. private static void SendCallback(IAsyncResult ar)
- 12. {
- 13.
- 14. // 从state对象中获取socket
- 15. Socket client = (Socket)ar.AsyncState;
- 16.
- 17. // 完成数据发送.
- 18. int bytesSent = client.EndSend(ar);
- 19. Console.WriteLine("Sent {0} bytes to server.", bytesSent);
- 20.
- 21. // 指示数据已经发送完成,主线程继续.
- 22. sendDone.Set();
- 23.
- 24. }