日期:2013-09-15  浏览次数:20532 次

异步服务器套接字示例


下面的示例程序创建一个接收来自客户端的连接请求的服务器。该服务器是用异步套接字生成的,因此在等待来自客户端的连接时不挂起服务器应用程序的执行。该应用程序接收来自客户端的字符串,在控制台显示该字符串,然后将该字符串回显到客户端。来自客户端的字符串必须包含字符串“<EOF>”,以发出表示消息结尾的信号。
 [C#]
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
 
// State object for reading client data asynchronously
public class StateObject {
   public Socket workSocket = null;       // Client  socket.
   public const int BufferSize = 1024;       // Size of receive buffer.
   public byte[] buffer = new byte[BufferSize]; // Receive buffer.
   public StringBuilder sb = new StringBuilder();  // Received data string.
}
 
public class AsynchronousSocketListener {
   
   // Incoming data from client.
   public static string data = null;
 
   // Thread signal.
   public static ManualResetEvent allDone = new ManualResetEvent(false);
 
   public AsynchronousSocketListener() {
   }
 
   public static void StartListening() {
      // Data buffer for incoming data.
      byte[] bytes = new Byte[1024];
 
      // Establish the local endpoint for the  socket.
      //   The DNS name of the computer
      //  running the listener is "host.contoso.com".
      IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
      IPAddress ipAddress = ipHostInfo.AddressList[0];
      IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
 
      // Create a TCP/IP  socket.
      Socket listener = new Socket(AddressFamily.InterNetwork,
         SocketType.Stream, ProtocolType.Tcp );
 
      // Bind the  socket to the local endpoint and listen for incoming connections.
      try {
         listener.Bind(localEndPoint);
         listener.Listen(100);
 
         while (true) {
            // Set the event to  nonsignaled state.
            allDone.Reset();
 
            // Start  an asynchronous socket to listen for connections.
            Console.WriteLine("Waiting for a connection...");
            listener.BeginAccept( 
               new AsyncCallback(AcceptCallback),
               listener );