同步客户端套接字示例
下面的示例程序创建一个连接到服务器的客户端。该客户端是用同步套接字生成的,因此挂起客户端应用程序的执行,直到服务器返回响应为止。该应用程序将字符串发送到服务器,然后在控制台显示该服务器返回的字符串。
C#
usingSystem;
usingSystem.Net;
usingSystem.Net.Sockets;
usingSystem.Text;
publicclassSynchronousSocketClient{
publicstaticvoidStartClient(){
//Databufferforincomingdata.
byte[]bytes=newbyte[1024];
//Connecttoaremotedevice.
try{
//Establishtheremoteendpointforthesocket.
//Thisexampleusesport11000onthelocalcomputer.
IPHostEntryipHostInfo=Dns.Resolve(Dns.GetHostName())
IPAddressipAddress=ipHostInfo.AddressList[0];
IPEndPointremoteEP=newIPEndPoint(ipAddress,11000);
//CreateaTCP/IPsocket.
Socketsender=newSocket(AddressFamily.InterNetwork,
SocketType.Stream,ProtocolType.Tcp);
//Connectthesockettotheremoteendpoint.Catchanyerrors.
try{
sender.Connect(remoteEP);
Console.WriteLine("Socketconnectedto{0}",
sender.RemoteEndPoint.ToString());
//Encodethedatastringintoabytearray.
byte[]msg=Encoding.ASCII.GetBytes("Thisisatest<EOF>");
//Sendthedatathroughthesocket.
intbytesSent=sender.Send(msg);
//Receivetheresponsefromtheremotedevice.
intbytesRec=sender.Receive(bytes);
Console.WriteLine("Echoedtest={0}",
Encoding.ASCII.GetString(bytes,0,bytesRec));
//Releasethesocket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}catch(ArgumentNullExceptionane){
Console.WriteLine("ArgumentNullException:{0}",ane.ToString());
}catch(SocketExceptionse){
Console.WriteLine("SocketException:{0}",se.ToString());
}catch(Exceptione){
Console.WriteLine("Unexpectedexception:{0}",e.ToString());
}
}catch(Exceptione){
Console.WriteLine(e.ToString());
}
}
publicstaticintMain(String[]args){
StartClient();
return0;
}
}
同步服务器套接字示例下面的示例程序创建一个接收来自客户端的连接请求的服务器。该服务器是用同步套接字生成的,
因此在等待来自客户端的连接时挂起服务器应用程序的执行。该应用程序接收来自客户端的字符串,
在控制台显示该字符串,然后将该字符串回显到客户端。来自客户端的字符串必须包含字符串“<EOF>”,
以发出表示消息结尾的信号。
C#
复制代码
usingSystem;
usingSystem.Net;
usingSystem.Net.Sockets;
usingSystem.Text;
publicclassSynchronousSocketListener{
//Incomingdatafromtheclient.
publicstaticstringdata=null;
publicstaticvoidStartListening(){
//Databufferforincomingdata.
byte[]bytes=newByte[1024];
//Establishthelocalendpointforthesocket.
//Dns.GetHostNamereturnsthenameofthe
//hostrunningtheapplication.
IPHostEntryipHostInfo=Dns.Resolve(Dns.GetHostName());
IPAddressipAddress=ipHostInfo.AddressList[0];
IPEndPointlocalEndPoint=newIPEndPoint(ipAddress,11000);
//CreateaTCP/IPsocket.
Socketlistener=newSocket(AddressFamily.InterNetwork,
SocketType.Stream,ProtocolType.Tcp);
//Bindthesockettothelocalendpointand
//listenforincomingconnections.
try{
listener.Bind(localEndPoint);
listener.Listen(10);
//Startlisteningforconnections.
while(true){
Console.WriteLine("Waitingforaconnection...");
//Programissuspendedwhilewaitingforanincomingconnection.
Sockethandler=listener.Accept();
data=null;
//Anincomingconnectionneedstobeprocessed.
while(true){
bytes=newbyte[1024];
intbytesRec=handler.Receive(bytes);
data+=Encoding.ASCII.GetString(bytes,0,bytesRec);
if(data.IndexOf("<EOF>")>-1){
break;
}
}
//Showthedataontheconsole.
Console.WriteLine("Textreceived:{0}",data);
//Echothedatabacktotheclient.
byte[]msg=Encoding.ASCII.GetBytes(data);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}catch(Exceptione){
Console.WriteLine(e.ToString());
}
Console.WriteLine("nPressENTERtocontinue...");
Console.Read();
}
publicstaticintMain(String[]args){
StartListening();
return0;
}
}