异步socket的线程分配(C#)

本文介绍了一个使用C#进行异步Socket编程的例子,通过跟踪线程ID的方式展示了异步Socket如何分配线程来处理客户端连接请求及数据收发。
异步socket的线程分配(C#)

以下是MSDN里异步socket示例的代码,我在代码里加入了显示当前线程ID的语句,想看看异步socket的线程是怎么分配的,与客户端配合运行后的结果如图

Code
<!--<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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值