使用.NET访问Internet(4) Paul_Ni(原作)(补充)

<script type="text/javascript"> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
<script type="text/javascript"> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
开始从客户端套接字接收数据的 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.Inter NETwork,
        SocketType.Stream, ProtocolType.Tcp );

      // Connect the socket to the remote endpoint. Catch any errors.
      try {
        sender.Connect(remoteEP);

        Console.WriteLine("Socket connected to {0}",
          sender.RemoteEndPoint.ToString());

        // Encode the data string into a byte array.
        byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");

        // Send the data through the  socket.
        int bytesSent = sender.Send(msg);

        // Receive the response from the remote device.
        int bytesRec = sender.Receive(bytes);
        Console.WriteLine("Echoed test = {0}",
          Encoding.ASCII.GetString(bytes,0,bytesRec));

        // Release the socket.
        sender.Shutdown(SocketShutdown.Both);
        sender.Close();
        
      } catch (ArgumentNullException ane) {
        Console.WriteLine("ArgumentNullException : {0}",ane.ToString());
      } catch (SocketException se) {
        Console.WriteLine("SocketException : {0}",se.ToString());
      } catch (Exception e) {
        Console.WriteLine("Unexpected exception : {0}", e.ToString());
      }

    } catch (Exception e) {
      Console.WriteLine( e.ToString());
    }
  }
  
  public static int Main(String[] args) {
    StartClient();
    return 0;
  }<



<script type="text/javascript"> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
<script type="text/javascript"> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值