首页 > 开发 > 综合 > 正文

续实例解析SOCKET编程模型之异步通信篇(下)

2024-07-21 02:23:36
字体:
来源:转载
供稿:网友
异步客户端套接字在等待网络操作完成时不挂起应用程序。相反,它使用标准 .net framework 异步编程模型在一个线程上处理网络连接,而应用程序继续在原始线程上运行。异步套接字适用于大量使用网络或不能等待网络操作完成才能继续的应用程序。

socket 类遵循异步方法的 .net framework 命名模式;例如,同步 receive 方法对应异步 beginreceive 和 endreceive 方法。

异步操作要求回调方法返回操作结果。如果应用程序不需要知道结果,则不需要任何回调方法。本节中的代码示例阐释如何使用某个方法开始与网络设备的连接并使用回调方法结束连接,如何使用某个方法开始发送数据并使用回调方法完成发送,以及如何使用某个方法开始接收数据并使用回调方法结束接收数据。

异步套接字使用多个系统线程池中的线程处理网络连接。一个线程负责初始化数据的发送或接收;其他线程完成与网络设备的连接并发送或接收数据。在程序源码中,system.threading.manualresetevent 类的实例用于挂起主线程的执行并在执行可以继续时发出信号。

在客户端源码中,为了将异步套接字连接到网络设备,socket 方法初始化一个 socket,然后调用 beginconnect 方法,传递表示网络设备的远程终结点、连接回调方法以及状态对象(即客户端 socket,用于在异步调用之间传递状态信息)。该示例实现 connect 方法以将指定的 socket 连接到指定的终结点。它采用一个名为 connectdone 的全局 manualresetevent: public iasyncresult beginconnect(
endpoint remoteep,
asynccallback callback,
object state
);

连接回调方法 connectcallback 实现 asynccallback 委托。它在远程设备可用时连接到远程设备,然后通过设置 manualresetevent connectdone 向应用程序线程发出连接完成的信号。下面的客户端源码中实现了 connectcallback 方法。

send 示例方法以 ascii 格式对指定的字符串数据进行编码,并将其异步发送到指定的套接字所表示的网络设备。

发送回调方法 sendcallback 实现 asynccallback 委托。它在网络设备准备接收时发送数据。下面的源码中实现了 sendcallback 方法。它采用一个名为 senddone 的全局 manualresetevent。

从客户端套接字读取数据需要一个在异步调用之间传递值的状态对象。下面的类是用于从客户端套接字接收数据的示例状态对象。它包含以下各项的字段:客户端套接字,用于接收数据的缓冲区,以及用于保存传入数据字符串的 stringbuilder。将这些字段放在该状态对象中,使这些字段的值在多个调用之间得以保留,以便从客户端套接字读取数据。

public class stateobject {
// client socket.
public socket worksocket = null;
// size of receive buffer.
public const int buffersize = 256;
// receive buffer.
public byte[] buffer = new byte[buffersize];
// received data string.
public stringbuilder sb = new stringbuilder();
} //为简单起见,客户端源码中并未创建此类

receive 方法示例设置状态对象,然后调用 beginreceive 方法从客户端套接字异步读取数据。

接收回调方法 receivecallback 实现 asynccallback 委托。它接收来自网络设备的数据并生成消息字符串。它将来自网络的一个或多个数据字节读入数据缓冲区,然后再次调用 beginreceive 方法,直到客户端发送的数据完成为止。从客户端读取所有数据后,receivecallback 通过设置 manualresetevent senddone 向应用程序线程发出数据完成的信号。

//以下是客户端详细实现代码

using system;
using system.drawing;
using system.collections;
using system.componentmodel;
using system.windows.forms;
using system.data;
using system.net;
using system.net.sockets;
using system.threading;
using system.text;
namespace 聊天_socket_client
{
/// <summary>
/// form1 的摘要说明。
/// </summary>
public class form1 : system.windows.forms.form
{
private system.windows.forms.label label4;
private system.windows.forms.label label3;
private system.windows.forms.label label2;
private system.windows.forms.label label1;
private system.windows.forms.button btnstop;
private system.windows.forms.button btnsend;
private system.windows.forms.textbox txtport;
private system.windows.forms.textbox txtserver;
private system.windows.forms.richtextbox rtbsend;
private system.windows.forms.richtextbox rtbreceive;
private system.windows.forms.statusbar statusbar1;
private system.windows.forms.button btnconnect;
private ipaddress hostipaddress;
private ipendpoint server;
private socket sock;
private const int buffersize=256;
private byte[] buffer=new byte[buffersize];
private static manualresetevent connectdone=new manualresetevent(false);
private static manualresetevent senddone=new manualresetevent(false);
/// <summary>
/// 必需的设计器变量。
/// </summary>
private system.componentmodel.container components = null;

public form1()
{
//
// windows 窗体设计器支持所必需的
//
initializecomponent();

//
// todo: 在 initializecomponent 调用后添加任何构造函数代码
//
}

/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.dispose();
}
}
base.dispose( disposing );
}

#region windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void initializecomponent()
{
this.label4 = new system.windows.forms.label();
this.label3 = new system.windows.forms.label();
this.label2 = new system.windows.forms.label();
this.label1 = new system.windows.forms.label();
this.btnstop = new system.windows.forms.button();
this.btnsend = new system.windows.forms.button();
this.btnconnect = new system.windows.forms.button();
this.txtport = new system.windows.forms.textbox();
this.txtserver = new system.windows.forms.textbox();
this.rtbsend = new system.windows.forms.richtextbox();
this.rtbreceive = new system.windows.forms.richtextbox();
this.statusbar1 = new system.windows.forms.statusbar();
this.suspendlayout();
//
// label4
//
this.label4.location = new system.drawing.point(16, 152);
this.label4.name = "label4";
this.label4.size = new system.drawing.size(64, 23);
this.label4.tabindex = 22;
this.label4.text = "发送信息:";
//
// label3
//
this.label3.location = new system.drawing.point(16, 64);
this.label3.name = "label3";
this.label3.size = new system.drawing.size(64, 23);
this.label3.tabindex = 21;
this.label3.text = "接收信息:";
//
// label2
//
this.label2.location = new system.drawing.point(216, 16);
this.label2.name = "label2";
this.label2.size = new system.drawing.size(64, 23);
this.label2.tabindex = 20;
this.label2.text = "监听端口:";
//
// label1
//
this.label1.location = new system.drawing.point(16, 16);
this.label1.name = "label1";
this.label1.size = new system.drawing.size(56, 23);
this.label1.tabindex = 19;
this.label1.text = "服务器:";
//
// btnstop
//
this.btnstop.location = new system.drawing.point(256, 256);
this.btnstop.name = "btnstop";
this.btnstop.tabindex = 18;
this.btnstop.text = "关闭连接";
this.btnstop.click += new system.eventhandler(this.btnstop_click);
//
// btnsend
//
this.btnsend.location = new system.drawing.point(144, 256);
this.btnsend.name = "btnsend";
this.btnsend.tabindex = 17;
this.btnsend.text = "发送信息";
this.btnsend.click += new system.eventhandler(this.btnsend_click);
//
// btnconnect
//
this.btnconnect.location = new system.drawing.point(32, 256);
this.btnconnect.name = "btnconnect";
this.btnconnect.tabindex = 16;
this.btnconnect.text = "请求连接";
this.btnconnect.click += new system.eventhandler(this.btnconnect_click);
//
// txtport
//
this.txtport.location = new system.drawing.point(288, 16);
this.txtport.name = "txtport";
this.txtport.size = new system.drawing.size(48, 21);
this.txtport.tabindex = 15;
this.txtport.text = "19811";
//
// txtserver
//
this.txtserver.location = new system.drawing.point(72, 16);
this.txtserver.name = "txtserver";
this.txtserver.tabindex = 14;
this.txtserver.text = "127.0.0.1";
//
// rtbsend
//
this.rtbsend.location = new system.drawing.point(80, 152);
this.rtbsend.name = "rtbsend";
this.rtbsend.size = new system.drawing.size(264, 96);
this.rtbsend.tabindex = 13;
this.rtbsend.text = "";
//
// rtbreceive
//
this.rtbreceive.location = new system.drawing.point(80, 56);
this.rtbreceive.name = "rtbreceive";
this.rtbreceive.size = new system.drawing.size(264, 96);
this.rtbreceive.tabindex = 12;
this.rtbreceive.text = "";
//
// statusbar1
//
this.statusbar1.location = new system.drawing.point(0, 287);
this.statusbar1.name = "statusbar1";
this.statusbar1.showpanels = true;
this.statusbar1.size = new system.drawing.size(360, 22);
this.statusbar1.tabindex = 23;
this.statusbar1.text = "statusbar1";
//
// form1
//
this.autoscalebasesize = new system.drawing.size(6, 14);
this.clientsize = new system.drawing.size(360, 309);
this.controls.add(this.statusbar1);
this.controls.add(this.label4);
this.controls.add(this.label3);
this.controls.add(this.label2);
this.controls.add(this.label1);
this.controls.add(this.btnstop);
this.controls.add(this.btnsend);
this.controls.add(this.btnconnect);
this.controls.add(this.txtport);
this.controls.add(this.txtserver);
this.controls.add(this.rtbsend);
this.controls.add(this.rtbreceive);
this.name = "form1";
this.text = "聊天程序-客户端";
this.closing += new system.componentmodel.canceleventhandler(this.form1_closing);
this.resumelayout(false);

}
#endregion

/// <summary>
/// 应用程序的主入口点。
/// </summary>
[stathread]
static void main()
{
application.run(new form1());
}

private void btnconnect_click(object sender, system.eventargs e)
{
try
{
hostipaddress=ipaddress.parse(txtserver.text);
}
catch{messagebox.show("请输入正确的ip地址格式。");}
try
{
server=new ipendpoint(hostipaddress,int32.parse(txtport.text));
sock=new socket(addressfamily.internetwork,sockettype.stream,protocoltype.tcp);
sock.beginconnect(server,new asynccallback(connectcallback),sock);
}
catch(exception ee){messagebox.show(ee.message);}
}
private void connectcallback(iasyncresult ar)
{
try
{
socket client=(socket)ar.asyncstate; //获取状态
client.endconnect(ar);
try
{
byte[] bytedata=encoding.bigendianunicode.getbytes("准备完毕,可以通话"+"/r/n");
sock.beginsend(bytedata,0,bytedata.length,0,new asynccallback(sendcallback),sock);
}
catch(exception ee){messagebox.show(ee.message);}
statusbar1.text="与主机"+txtserver.text+"端口"+txtport.text+"连接成功";
thread thread=new thread(new threadstart(threadproc));
thread.start(); //开始接收数据线程
connectdone.set(); //将指定事件的状态设置为终止。
}
catch{}
}
private void sendcallback(iasyncresult ar)
{
try{
socket client=(socket)ar.asyncstate;
senddone.set();
}
catch(exception ee){messagebox.show(ee.message);}
}
private void threadproc()
{
try
{
sock.beginreceive(buffer,0,buffersize,0,new asynccallback(receivecallback),sock);
}
catch(exception ee){messagebox.show(ee.message);}
}
private void receivecallback(iasyncresult ar)
{
try
{
socket client=(socket)ar.asyncstate;
int bytesread=client.endreceive(ar);//结束挂起的异步读取。返回接收到的字节数。
stringbuilder sb=new stringbuilder();
sb.append(encoding.bigendianunicode.getstring(buffer,0,bytesread));//储存数据
string content=sb.tostring(); //转换为字符串
sb.remove(0,content.length); //清除sb内容
rtbreceive.appendtext(content+"/r/n");
client.beginreceive(buffer,0,buffersize,0,new asynccallback(receivecallback),client);
}
catch{}
}

private void btnsend_click(object sender, system.eventargs e)
{
try
{
string strsend ="client--->"+rtbsend.text+"/r/n";
byte[] bytesend = encoding.bigendianunicode.getbytes(strsend);
sock.beginsend(bytesend,0,bytesend.length,0,new asynccallback(sendcallback),sock);
}
catch{messagebox.show("连接尚未建立,无法发送.");}
}

private void btnstop_click(object sender, system.eventargs e)
{
try
{
sock.close();
statusbar1.text="与主机"+txtserver.text+"端口"+txtport.text+"断开连接";
}
catch{messagebox.show("连接尚未建立,关闭无效");}
}

private void form1_closing(object sender, system.componentmodel.canceleventargs e)
{
try
{
sock.close();
}
catch{}
}
}
}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表