两种服务器socket异步监听的比较??

kevinfjc 2005-07-24 08:56:34
我在写一个web的代理服务器,我想要不断的监听
客户端发来的请求,请问下面两种方法比较好??


btw:截获到的客户端socket是要作为参数传递到proxy类的

////////////////////////////////////////////////第一种
socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
IPEndPoint iep=new IPEndPoint(IPAddress.Any,8000);

socket.Bind(iep);
socket.Listen(10);

Thread th1=new Thread(new ThreadStart(AcceptConnection1));
th1.Start();

/////
private void AcceptConnection1()
{
while (true)
{
Done.Reset();
this.socket.BeginAccept(new AsyncCallback(AcceptConnection2),this.socket);

Done.WaitOne();
}

}

////
private void AcceptConnection2(IAsyncResult ar)
{

Done.Set();

Socket server=(Socket)ar.AsyncState;

Socket client=server.EndAccept(ar);

Proxy proxy=new Proxy(client);

Thread thread=new Thread(new ThreadStart(proxy.Run));
thread.Start();

}
//////////////////////////////////第二种

socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
IPEndPoint iep=new IPEndPoint(IPAddress.Any,8000);

socket.Bind(iep);
socket.Listen(10);

Thread th1=new Thread(new ThreadStart(AcceptConnection1));
th1.Start();

/////
private void AcceptConnection1()
{

Done.Reset();
this.socket.BeginAccept(new AsyncCallback(AcceptConnection2),this.socket);

Done.WaitOne();


}

////
private void AcceptConnection2(IAsyncResult ar)
{

Done.Set();

Socket server=(Socket)ar.AsyncState;

Socket client=server.EndAccept(ar);

Proxy proxy=new Proxy(client);

Thread thread=new Thread(new ThreadStart(proxy.Run));
thread.Start();
this.socket.BeginAccept(new AsyncCallback(AcceptConnection2),this.socket);

}
...全文
418 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
JzeroBiao 2005-07-24
  • 打赏
  • 举报
回复
第一种
wangsaokui 2005-07-24
  • 打赏
  • 举报
回复
第一种好,因为第二种中
private void AcceptConnection2(IAsyncResult ar)
{

Done.Set();
此句将立刻将ManualResetEvent的WaitOne 的调用立即返回,AcceptConnection1()将结束,
AcceptConnection2中的this.socket.BeginAccept(new AsyncCallback(AcceptConnection2),this.socket);
将继续执行监听,并在接收连接后继续执行AcceptConnection2,但此时的Done已经结束了,Done.Set()没有任何意义,是个隐患。

第一种采用循环方式,每次开始前先Done.Reset();线程的WaitOne是有保障的。

所以第一种好。
dazhu2 2005-07-24
  • 打赏
  • 举报
回复
第一种

110,539

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧