使用.NET访问Internet(4) Paul_Ni(原作)(补充)
2024-07-10 12:58:29
供稿:网友
菜鸟学堂:
开始从客户端套接字接收数据的 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,
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;
}
}