日期:2011-02-11  浏览次数:20436 次

开始从客户端套接字接收数据的 acceptCallback 方法的此节首先初始化 StateObject 类的一个实例,然后调用 BeginReceive 方法以开始从客户端套接字异步读取数据。

下面的示例显示了完整的 acceptCallback 方法。它假定以下内容:存在一个名为 allDone 的 ManualResetEvent 实例,定义了 StateObject 类,以及在名为 SocketListener 的类中定义了 readCallback 方法。

[C#]
  public static void acceptCallback(IAsyncResult ar) {
    // Get the socket that handles the client request.
    Socket listener = (Socket) ar.AsyncState;
    Socket handler = listener.EndAccept(ar);

    // Signal the main thread to continue.
    allDone.Set();

    // Create the state object.
    StateObject state = new StateObject();
    state.workSocket = handler;
    handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,
      new AsyncCallback(AsynchronousSocketListener.readCallback), state);
  }
需要为异步套接字服务器实现的 final 方法是返回客户端发送的数据的读取回调方法。与接受回调方法一样,读取回调方法也是一个 AsyncCallback 委托。该方法将来自客户端套接字的一个或多个字节读入数据缓冲区,然后再次调用 BeginReceive 方法,直到客户端发送的数据完成为止。从客户端读取整个消息后,在控制台上显示字符串,并关闭处理与客户端的连接的服务器套接字。

下面的示例实现 readCallback 方法。它假定定义了 StateObject 类。

[C#]
public void readCallback(IAsyncResult ar) {
  StateObject state = (StateObject) ar.AsyncState;
  Socket handler = state.WorkSocket;

  // Read data from the client socket.
  int read = handler.EndReceive(ar);

  // Data was read from the client socket.
  if (read > 0) {
    state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,read));
    handler.BeginReceive(state.buffer,0,StateObject.BufferSize, 0,
      new AsyncCallback(readCallback), state);
  } else {
    if (state.sb.Length > 1) {
      // All the data has been read from the client;
      // display it on the console.
      string content = state.sb.ToString();
      Console.WriteLine("Read {0} bytes from socket.\n Data : {1}",
        content.Length, content);
    }
    handler.Close();
  }
}
同步客户端套接字示例
下面的示例程序创建一个连接到服务器的客户端。该客户端是用同步套接字生成的,因此挂起客户端应用程序的执行,直到服务器返回响应为止。该应用程序将字符串发送到服务器,然后在控制台显示该服务器返回的字符串。

[C#]
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class SynchronousSocketClient {

  public static void StartClient() {
    // Data buffer for incoming data.
    byte[] bytes = new byte[1024];

    // 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,11000);

      // Create a TCP/IP  socket.
      Socket sender = new Socket(AddressFamily.InterNetwork,