网站方案 软件方案
软件案例
公司系列站点: 软件开发 网站建设
服务从兢鑫开始 !
公司介绍 解决方案 成功案例 技术支持 知识中心 合作伙伴 访客留言
   首页  >  技术支持
Net技术
用套接字进行侦听
使用异步客户端套接字
为什么只使用DataReader
刷新aspx页面的六种方法
在C#.net中如何操作XML
ASP.NET 2.0中CSS失...
C#中判断空字符串的3种方法性能分析
.Net下实现分布式缓存同步的手段
Java技术
Jstl的函数库
深入Struts 1.1
java设计模式之Decorator
JSP SmartUpload上...
java设计模式之Memento
关于C#、java泛型的看法
数据库类
小巧的SQLserver存储过程分页
存储过程简介
网络知识
Win2000与Exchange...
OS(operating sys...
网络系统中的新技术
网络路由技术基础
什么是 ASP.NET
几种网络语言的比较
Ajax技术:构建动态的Java...
XML在Web中的简单应用
其它技术
电子邮件的特点
什么是Internet域名
常见木马和 未授权控制软件的关闭
开源精神的化身――Linux
美好的软件行业和苦难的程序员(一)
什么是网络广告?
个人站长必须记住的10个关键词
经营个人网站“五部曲”
 
Java技术
 
使用异步客户端套接字

异步客户端套接字在等待网络操作完成时不挂起应用程序。相反,它使用标准 .NET 框架异步编程模型在一个线程上处理网络连接,而应用程序继续在原始线程上运行。异步套接字适用于大量使用网络或不能等待网络操作完成才能继续的应用程序。
Socket 类遵循异步方法的 .NET 框架命名模式;例如,同步 Receive 方法对应异步 BeginReceive 和 EndReceive 方法。
异步操作要求回调方法返回操作结果。如果应用程序不需要知道结果,则不需要任何回调方法。本节中的代码示例阐释如何使用某个方法开始与网络设备的连接并使用回调方法结束连接,如何使用某个方法开始发送数据并使用回调方法完成发送,以及如何使用某个方法开始接收数据并使用回调方法结束接收数据。
异步套接字使用多个系统线程池中的线程处理网络连接。一个线程负责初始化数据的发送或接收;其他线程完成与网络设备的连接并发送或接收数据。在下列示例中,System.Threading.ManualResetEvent 类的实例用于挂起主线程的执行并在执行可以继续时发出信号。
在下面的示例中,为了将异步套接字连接到网络设备,Connect 方法初始化 Socket 实例,然后调用 BeginConnect 方法,传递表示网络设备的远程终结点、连接回调方法以及状态对象(即客户端 Socket 实例,用于在异步调用之间传递状态信息)。该示例实现 Connect 方法以将指定的 Socket 实例连接到指定的终结点。它假定存在一个名为 connectDone 的全局 ManualResetEvent。 [C#]
public static void Connect(EndPoint remoteEP, Socket client) {
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client );

connectDone.WaitOne();
}

连接回调方法 ConnectCallback 实现 AsyncCallback 委托。它在远程设备可用时连接到远程设备,然后通过设置 ManualResetEvent connectDone 向应用程序线程发出连接完成的信号。下面的代码实现 ConnectCallback 方法。 [C#]
private static void ConnectCallback(IAsyncResult ar) {
try {
// Retrieve the socket from the state object.
Socket client = (Socket) ar.AsyncState;

// Complete the connection.
client.EndConnect(ar);

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

// Signal that the connection has been made.
connectDone.Set();
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}

Send 示例方法以 ASCII 格式对指定的字符串数据进行编码,并将其异步发送到指定的套接字所表示的网络设备。下面的示例实现 Send 方法。 [C#]
private static void Send(Socket client, String data) {
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);

// Begin sending the data to the remote device.
client.BeginSend(byteData, 0, byteData.Length, SocketFlags.None,
new AsyncCallback(SendCallback), client);
}

发送回调方法 SendCallback 实现 AsyncCallback 委托。它在网络设备准备接收时发送数据。下面的示例显示 SendCallback 方法的实现。它假定存在一个名为 sendDone 的全局 ManualResetEvent 实例。 [C#]
private static void SendCallback(IAsyncResult ar) {
try {
// Retrieve the socket from the state object.
Socket client = (Socket) ar.AsyncState;

// Complete sending the data to the remote device.
int bytesSent = client.EndSend(ar);
Console.WriteLine("Sent {0} bytes to server.", bytesSent);

// Signal that all bytes have been sent.
sendDone.Set();
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}

从客户端套接字读取数据需要一个在异步调用之间传递值的状态对象。下面的类是用于从客户端套接字接收数据的示例状态对象。它包含以下各项的字段:客户端套接字,用于接收数据的缓冲区,以及用于保存传入数据字符串的 StringBuilder。将这些字段放在该状态对象中,使这些字段的值在多个调用之间得以保留,以便从客户端套接字读取数据。 [C#]
public class StateObject {
public Socket workSocket = null; // Client socket.
public const int BufferSize = 256; // Size of receive buffer.
public byte[] buffer = new byte[BufferSize]; // Receive buffer.
public StringBuilder sb = new StringBuilder();// Received data string.
}

Receive 方法示例设置状态对象,然后调用 BeginReceive 方法从客户端套接字异步读取数据。下面的示例实现 Receive 方法。 [C#]
private static void Receive(Socket client) {
try {
// Create the state object.
StateObject state = new StateObject();
state.workSocket = client;

// Begin receiving the data from the remote device.
client.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}

接收回调方法 ReceiveCallback 实现 AsyncCallback 委托。它接收来自网络设备的数据并生成消息字符串。它将来自网络的一个或多个数据字节读入数据缓冲区,然后再次调用 BeginReceive 方法,直到客户端发送的数据完成为止。从客户端读取所有数据后,ReceiveCallback 通过设置 ManualResetEvent sendDone 向应用程序线程发出数据完成的信号。
下面的示例代码实现 ReceiveCallback 方法。它假定存在一个名为 response 的全局字符串(该字符串保存接收的字符串)和一个名为 receiveDone 的全局 ManualResetEvent 实例。服务器必须正常关闭客户端套接字以结束网络会话。 [C#]
private static void ReceiveCallback( IAsyncResult ar ) {
try {
// Retrieve the state object and the client socket
// from the async state object.
StateObject state = (StateObject) ar.AsyncState;
Socket client = state.workSocket;
// Read data from the remote device.
int bytesRead = client.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));
// Get the rest of the data.
client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,
new AsyncCallback(ReceiveCallback), state);
} else {
// All the data has arrived; put it in response.
if (state.sb.Length > 1) {
response = state.sb.ToString();
}
// Signal that all bytes have been received.
receiveDone.Set();
}
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
 
首 页 | 关于我们 | 解决方案 | 网站建设 | 软件方案 | 联系我们
互联网许可证:沪ICP07015503    版权所有:上海兢鑫软件有限公司  法律顾问:游本刚律师
总机电话:021-64864161 业务一:021-64390567 业务二:021-64812796 传真:+86[21]64812797 邮编:200030 
公司地址:中国 上海 徐汇区零陵路585号爱邦大厦18楼B座(徐汇)   静安区新闸路1711号中国联通大厦3楼301室(静安)