异步服务器套接字示例
下面的示例程序创建一个接收来自客户端的连接请求的服务器。该服务器是用异步套接字生成的,因此在等待来自客户端的连接时不挂起服务器应用程序的执行。该应用程序接收来自客户端的字符串,在控制台显示该字符串,然后将该字符串回显到客户端。来自客户端的字符串必须包含字符串“<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 );
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
} catch (Exception e) {Console.WriteLine(e.ToString());
}
Console.WriteLine("\nHit enter to continue...");Console.Read();
}
public static void AcceptCallback(IAsyncResult ar) {// Signal the main thread to continue.
allDone.Set();
// Get the socket that handles the client request.
Socket listener = (Socket) ar.AsyncState;
Socket handler = listener.EndAccept(ar);
// Create the state object.
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
public static void ReadCallback(IAsyncResult ar) {String content = String.Empty;
// Retrieve the state object and the handler socket
// from the async state object.
StateObject state = (StateObject) ar.AsyncState;
Socket handler = state.workSocket;
// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0) {// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(
state.buffer,0,bytesRead));
// Check for end-of-file tag. If it is not there, read
// more data.
content = state.sb.ToString();
if (content.IndexOf("<EOF>") > -1) {// All the data has been read from the
// client. Display it on the console.
 保留地址 http://www.qqread.com/dotnet/u236930.html更多内容请看.NET移动与嵌入式技术、.NET开发手册、.NET实用开发专题,或进入讨论组讨论。
相关图文阅读
频道图文推荐
健 康 咨 询
时 尚 咨 询
相关专题
- .NET移动与嵌入式技术 (5882篇文章)
- .NET开发手册 (5587篇文章)
- .NET实用开发 (1653篇文章)
- VB.NET 入门教程 (22167次浏览)
- asp.net 实现购物车详细代码 (14312次浏览)
- C#版的网站新闻发布系统 (690次浏览)
- ASP.NET2.0轻松搞定统计图表 (651次浏览)
- 使用ASP.NET AJAX实现幻灯片效果 (604次浏览)
- ASP.NET如何存取 SQLServer数据库图片 (592次浏览)
- 如何制作Asp.Net界面模板 (582次浏览)
- ASP.NET中实现DataGrid数据排序 (580次浏览)
- VB.NET读写文本文件方法 (579次浏览)
- VC#初学入门:第一个Windows程序 (536次浏览)



