手机
当前位置:查字典教程网 >编程开发 >C#教程 >c#(Socket)异步套接字代码示例
c#(Socket)异步套接字代码示例
摘要:异步客户端套接字示例下面的示例程序创建一个连接到服务器的客户端。该客户端是用异步套接字生成的,因此在等待服务器返回响应时不挂起客户端应用程序...

异步客户端套接字示例

下面的示例程序创建一个连接到服务器的客户端。该客户端是用异步套接字生成的,因此在等待服务器返回响应时不挂起客户端应用程序的执行。该应用程序将字符串发送到服务器,然后在控制台显示该服务器返回的字符串。

C#

usingSystem;

usingSystem.Net;

usingSystem.Net.Sockets;

usingSystem.Threading;

usingSystem.Text;

//Stateobjectforreceivingdatafromremotedevice.

publicclassStateObject{

//Clientsocket.

publicSocketworkSocket=null;

//Sizeofreceivebuffer.

publicconstintBufferSize=256;

//Receivebuffer.

publicbyte[]buffer=newbyte[BufferSize];

//Receiveddatastring.

publicStringBuildersb=newStringBuilder();

}

publicclassAsynchronousClient{

//Theportnumberfortheremotedevice.

privateconstintport=11000;

//ManualResetEventinstancessignalcompletion.

privatestaticManualResetEventconnectDone=

newManualResetEvent(false);

privatestaticManualResetEventsendDone=

newManualResetEvent(false);

privatestaticManualResetEventreceiveDone=

newManualResetEvent(false);

//Theresponsefromtheremotedevice.

privatestaticStringresponse=String.Empty;

privatestaticvoidStartClient(){

//Connecttoaremotedevice.

try{

//Establishtheremoteendpointforthesocket.

//Thenameofthe

//remotedeviceis"host.contoso.com".

IPHostEntryipHostInfo=Dns.Resolve("host.contoso.com");

IPAddressipAddress=ipHostInfo.AddressList[0];

IPEndPointremoteEP=newIPEndPoint(ipAddress,port);

//CreateaTCP/IPsocket.

Socketclient=newSocket(AddressFamily.InterNetwork,

SocketType.Stream,ProtocolType.Tcp);

//Connecttotheremoteendpoint.

client.BeginConnect(remoteEP,

newAsyncCallback(ConnectCallback),client);

connectDone.WaitOne();

//Sendtestdatatotheremotedevice.

Send(client,"Thisisatest<EOF>");

sendDone.WaitOne();

//Receivetheresponsefromtheremotedevice.

Receive(client);

receiveDone.WaitOne();

//Writetheresponsetotheconsole.

Console.WriteLine("Responsereceived:{0}",response);

//Releasethesocket.

client.Shutdown(SocketShutdown.Both);

client.Close();

}catch(Exceptione){

Console.WriteLine(e.ToString());

}

}

privatestaticvoidConnectCallback(IAsyncResultar){

try{

//Retrievethesocketfromthestateobject.

Socketclient=(Socket)ar.AsyncState;

//Completetheconnection.

client.EndConnect(ar);

Console.WriteLine("Socketconnectedto{0}",

client.RemoteEndPoint.ToString());

//Signalthattheconnectionhasbeenmade.

connectDone.Set();

}catch(Exceptione){

Console.WriteLine(e.ToString());

}

}

privatestaticvoidReceive(Socketclient){

try{

//Createthestateobject.

StateObjectstate=newStateObject();

state.workSocket=client;

//Beginreceivingthedatafromtheremotedevice.

client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,

newAsyncCallback(ReceiveCallback),state);

}catch(Exceptione){

Console.WriteLine(e.ToString());

}

}

privatestaticvoidReceiveCallback(IAsyncResultar){

try{

//Retrievethestateobjectandtheclientsocket

//fromtheasynchronousstateobject.

StateObjectstate=(StateObject)ar.AsyncState;

Socketclient=state.workSocket;

//Readdatafromtheremotedevice.

intbytesRead=client.EndReceive(ar);

if(bytesRead>0){

//Theremightbemoredata,sostorethedatareceivedsofar.

state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));

//Gettherestofthedata.

client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,

newAsyncCallback(ReceiveCallback),state);

}else{

//Allthedatahasarrived;putitinresponse.

if(state.sb.Length>1){

response=state.sb.ToString();

}

//Signalthatallbyteshavebeenreceived.

receiveDone.Set();

}

}catch(Exceptione){

Console.WriteLine(e.ToString());

}

}

privatestaticvoidSend(Socketclient,Stringdata){

//ConvertthestringdatatobytedatausingASCIIencoding.

byte[]byteData=Encoding.ASCII.GetBytes(data);

//Beginsendingthedatatotheremotedevice.

client.BeginSend(byteData,0,byteData.Length,0,

newAsyncCallback(SendCallback),client);

}

privatestaticvoidSendCallback(IAsyncResultar){

try{

//Retrievethesocketfromthestateobject.

Socketclient=(Socket)ar.AsyncState;

//Completesendingthedatatotheremotedevice.

intbytesSent=client.EndSend(ar);

Console.WriteLine("Sent{0}bytestoserver.",bytesSent);

//Signalthatallbyteshavebeensent.

sendDone.Set();

}catch(Exceptione){

Console.WriteLine(e.ToString());

}

}

publicstaticintMain(String[]args){

StartClient();

return0;

}

}

异步服务器套接字示例下面的示例程序创建一个接收来自客户端的连接请求的服务器。该服务器是用异步套接字生成的,

因此在等待来自客户端的连接时不挂起服务器应用程序的执行。该应用程序接收来自客户端的字符串,

在控制台显示该字符串,然后将该字符串回显到客户端。来自客户端的字符串必须包含字符串“<EOF>”,

以发出表示消息结尾的信号。

C#

复制代码

usingSystem;

usingSystem.Net;

usingSystem.Net.Sockets;

usingSystem.Text;

usingSystem.Threading;

//Stateobjectforreadingclientdataasynchronously

publicclassStateObject{

//Clientsocket.

publicSocketworkSocket=null;

//Sizeofreceivebuffer.

publicconstintBufferSize=1024;

//Receivebuffer.

publicbyte[]buffer=newbyte[BufferSize];

//Receiveddatastring.

publicStringBuildersb=newStringBuilder();

}

publicclassAsynchronousSocketListener{

//Threadsignal.

publicstaticManualResetEventallDone=newManualResetEvent(false);

publicAsynchronousSocketListener(){

}

publicstaticvoidStartListening(){

//Databufferforincomingdata.

byte[]bytes=newByte[1024];

//Establishthelocalendpointforthesocket.

//TheDNSnameofthecomputer

//runningthelisteneris"host.contoso.com".

IPHostEntryipHostInfo=Dns.Resolve(Dns.GetHostName());

IPAddressipAddress=ipHostInfo.AddressList[0];

IPEndPointlocalEndPoint=newIPEndPoint(ipAddress,11000);

//CreateaTCP/IPsocket.

Socketlistener=newSocket(AddressFamily.InterNetwork,

SocketType.Stream,ProtocolType.Tcp);

//Bindthesockettothelocalendpointandlistenforincomingconnections.

try{

listener.Bind(localEndPoint);

listener.Listen(100);

while(true){

//Settheeventtononsignaledstate.

allDone.Reset();

//Startanasynchronoussockettolistenforconnections.

Console.WriteLine("Waitingforaconnection...");

listener.BeginAccept(

newAsyncCallback(AcceptCallback),

listener);

//Waituntilaconnectionismadebeforecontinuing.

allDone.WaitOne();

}

}catch(Exceptione){

Console.WriteLine(e.ToString());

}

Console.WriteLine("nPressENTERtocontinue...");

Console.Read();

}

publicstaticvoidAcceptCallback(IAsyncResultar){

//Signalthemainthreadtocontinue.

allDone.Set();

//Getthesocketthathandlestheclientrequest.

Socketlistener=(Socket)ar.AsyncState;

Sockethandler=listener.EndAccept(ar);

//Createthestateobject.

StateObjectstate=newStateObject();

state.workSocket=handler;

handler.BeginReceive(state.buffer,0,StateObject.BufferSize,0,

newAsyncCallback(ReadCallback),state);

}

publicstaticvoidReadCallback(IAsyncResultar){

Stringcontent=String.Empty;

//Retrievethestateobjectandthehandlersocket

//fromtheasynchronousstateobject.

StateObjectstate=(StateObject)ar.AsyncState;

Sockethandler=state.workSocket;

//Readdatafromtheclientsocket.

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);

//Echothedatabacktotheclient.

Send(handler,content);

}else{

//Notalldatareceived.Getmore.

handler.BeginReceive(state.buffer,0,StateObject.BufferSize,0,

newAsyncCallback(ReadCallback),state);

}

}

}

privatestaticvoidSend(Sockethandler,Stringdata){

//ConvertthestringdatatobytedatausingASCIIencoding.

byte[]byteData=Encoding.ASCII.GetBytes(data);

//Beginsendingthedatatotheremotedevice.

handler.BeginSend(byteData,0,byteData.Length,0,

newAsyncCallback(SendCallback),handler);

}

privatestaticvoidSendCallback(IAsyncResultar){

try{

//Retrievethesocketfromthestateobject.

Sockethandler=(Socket)ar.AsyncState;

//Completesendingthedatatotheremotedevice.

intbytesSent=handler.EndSend(ar);

Console.WriteLine("Sent{0}bytestoclient.",bytesSent);

handler.Shutdown(SocketShutdown.Both);

handler.Close();

}catch(Exceptione){

Console.WriteLine(e.ToString());

}

}

publicstaticintMain(String[]args){

StartListening();

return0;

}

}

【c#(Socket)异步套接字代码示例】相关文章:

c#获取本机的IP地址的代码

C# 注册表 操作实现代码

c# 图片加密解密的实例代码

c#的异或运算符介绍

c# 共享状态的文件读写实现代码

c# SQLHelper(for winForm)实现代码

用C#写的ADSL拨号程序的代码示例

c#典型工厂化实现实例

C# 撒列实现关键字过滤的实例

C#中字符串编码处理

精品推荐
分类导航