文档库

最新最全的文档下载
当前位置:文档库 > C_异步Socket

C_异步Socket

C#异步套接字实现浅析

C#异步套接字实现是如何的呢?让我们开始从实例开始:

下面的C#异步套接字实现实例程序创建一个连接到服务器的客户端。该客户端是用C#异步套接字生成的,因此在等待服务器返回响应时不挂起客户端应用程序的执行。该应用程序将字符串发送到服务器,然后在控制台显示该服务器返回的字符串。

1.

using System;

using http://www.wendangku.net/doc/e9934967783e0912a2162abb.html ;

using http://www.wendangku.net/doc/e9934967783e0912a2162abb.html .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.

免费下载Word文档免费下载: C_异步Socket

(共7页)