异步socket的线程分配(C#)
以下是MSDN里异步socket示例的代码,我在代码里加入了显示当前线程ID的语句,想看看异步socket的线程是怎么分配的,与客户端配合运行后的结果如图
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->
Server端代码:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.Net;
usingSystem.Net.Sockets;
usingSystem.Threading;

namespaceConsoleServer

{
publicclassStateObject

{
//Clientsocket.
publicSocketworkSocket=null;
//Sizeofreceivebuffer.
publicconstintBufferSize=1024;
//Receivebuffer.
publicbyte[]buffer=newbyte[BufferSize];
//Receiveddatastring.
publicStringBuildersb=newStringBuilder();
}

classProgram

{
publicstaticManualResetEventallDone=newManualResetEvent(false);

/**////<summary>
///监听
///并开始接受网络连接请求的方法
///</summary>
publicstaticvoidStartListening()

{
Console.WriteLine("监听时的线程:"+Thread.CurrentThread.ManagedThreadId.ToString());
//Databufferforincomingdata.
byte[]bytes=newByte[1024];
//Establishthelocalendpointforthesocket.
//TheDNSnameofthecomputer
//runningthelisteneris"host.contoso.com".
IPHostEntryipHostInfo=Dns.Resolve("127.0.0.1");
IPAddressipAddress=ipHostInfo.AddressList[0];
IPEndPointlocalEndPoint=newIPEndPoint(ipAddress,9090);
//创建一个tcp/ipsocket
Socketlistener=newSocket(AddressFamily.InterNetwork,
SocketType.Stream,ProtocolType.Tcp);
//Bindthesockettothelocalendpointandlistenforincomingconnections.
try

{
listener.Bind(localEndPoint);
Console.WriteLine("Listen1:"+Thread.CurrentThread.ManagedThreadId.ToString());
listener.Listen(100);
Console.WriteLine("Listen2:"+Thread.CurrentThread.ManagedThreadId.ToString());
while(true)

{
Console.WriteLine("1:"+Thread.CurrentThread.ManagedThreadId.ToString());
//Settheeventtononsignaledstate.设置为无信号状态
allDone.Reset();
Console.WriteLine("2:"+Thread.CurrentThread.ManagedThreadId.ToString());
//Startanasynchronoussockettolistenforconnections.
Console.WriteLine("Waitingforaconnection
");
//开始建立连接
listener.BeginAccept(
newAsyncCallback(AcceptCallback),
listener);
Console.WriteLine("3:"+Thread.CurrentThread.ManagedThreadId.ToString());
//Waituntilaconnectionismadebeforecontinuing.
allDone.WaitOne();
Console.WriteLine("4:"+Thread.CurrentThread.ManagedThreadId.ToString());
}
}
catch(Exceptione)

{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPressENTERtocontinue
");
Console.Read();
}

/**////<summary>
///处理连接请求
///并开始接收网络数据的回调方法
///</summary>
///<paramname="ar"></param>
publicstaticvoidAcceptCallback(IAsyncResultar)

{
//Signalthemainthreadtocontinue.
allDone.Set();
Console.WriteLine("AcceptCallback1线程ID为:"+Thread.CurrentThread.ManagedThreadId.ToString());
//Getthesocketthathandlestheclientrequest.
Socketlistener=(Socket)ar.AsyncState;
//建立socket通道,连接建立完成
Sockethandler=listener.EndAccept(ar);
//Createthestateobject.创建一个状态对象,开始接受数据
StateObjectstate=newStateObject();
state.workSocket=handler;
handler.BeginReceive(state.buffer,0,StateObject.BufferSize,0,
newAsyncCallback(ReadCallback),state);
Console.WriteLine("AcceptCallback2线程ID为:"+Thread.CurrentThread.ManagedThreadId.ToString());
}


/**////<summary>
///结束接收数据的回调方法
///</summary>
///<paramname="ar"></param>
publicstaticvoidReadCallback(IAsyncResultar)

{
Console.WriteLine("ReadCallback线程ID为:"+Thread.CurrentThread.ManagedThreadId.ToString());
Stringcontent=String.Empty;
//Retrievethestateobjectandthehandlersocket
//fromtheasynchronousstateobject.
StateObjectstate=(StateObject)ar.AsyncState;
Sockethandler=state.workSocket;
//Readdatafromtheclientsocket.从socket通道里读取数据
intbytesRead=handler.EndReceive(ar);
if(bytesRead>0)

{
//Theremightbemoredata,sostorethedatareceivedsofar.
state.sb.Append(Encoding.ASCII.GetString(
state.buffer,0,bytesRead));
//Checkforend-of-filetag.Ifitisnotthere,read
//moredata.
content=state.sb.ToString();
if(content.IndexOf("<EOF>")>-1)

{
//Allthedatahasbeenreadfromthe
//client.Displayitontheconsole.
Console.WriteLine("Read{0}bytesfromsocket.\nData:{1}",
content.Length,content);
Console.WriteLine("请输入要发送的信息:");
stringstr=Console.ReadLine();
Send(handler,str+"<EOF>");
//Send(handler,content);

}
else

{
//Notalldatareceived.Getmore.
handler.BeginReceive(state.buffer,0,StateObject.BufferSize,0,
newAsyncCallback(ReadCallback),state);
}
}
}


/**////<summary>
///开始发送数据的方法
///</summary>
///<paramname="handler"></param>
///<paramname="data"></param>
privatestaticvoidSend(Sockethandler,Stringdata)

{
//ConvertthestringdatatobytedatausingASCIIencoding.
byte[]byteData=Encoding.ASCII.GetBytes(data);
//Beginsendingthedatatotheremotedevice.
handler.BeginSend(byteData,0,byteData.Length,0,
newAsyncCallback(SendCallback),handler);
}


/**////<summary>
///结束发送数据的回调方法
///</summary>
///<paramname="ar"></param>
privatestaticvoidSendCallback(IAsyncResultar)

{
Console.WriteLine("SendCallback线程ID为:"+Thread.CurrentThread.ManagedThreadId.ToString());
try

{
//Retrievethesocketfromthestateobject.
Sockethandler=(Socket)ar.AsyncState;
//Completesendingthedatatotheremotedevice.
intbytesSent=handler.EndSend(ar);
Console.WriteLine("Sent{0}bytestoclient.",bytesSent);
//没有了这两句,server是发不出去的,为什么呢?
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch(Exceptione)

{
Console.WriteLine(e.ToString());
}
}

staticvoidMain(string[]args)

{
Console.WriteLine("main线程ID为:"+Thread.CurrentThread.ManagedThreadId.ToString());
StartListening();
Console.ReadLine();
}
}
}


客户端代码:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.Net.Sockets;
usingSystem.Threading;
usingSystem.Net;

namespaceWindowsClient

{
publicclassStateObject

{
//Clientsocket.
publicSocketworkSocket=null;
//Sizeofreceivebuffer.
publicconstintBufferSize=256;
//Receivebuffer.
本文介绍了一个使用C#进行异步Socket编程的例子,通过跟踪线程ID的方式展示了异步Socket如何分配线程来处理客户端连接请求及数据收发。
5497

被折叠的 条评论
为什么被折叠?



