Socket編程--簡單同步服務端與客戶端示例

以下同步示例全部使用tcp協議.

服務端示例:

示例程序创建一个接收来自客户端的连接请求的服务器。该服务器是用同步套接字生成的, 因此在等待来自客户端的连接时挂起服务器应用程序的执行。该应用程序接收来自客户端的字符串,在控制台显示该字符串,然后将该字符串回显到客户端。来自客户端的字符串必须包含字符串“<EOF>”,以发出表示消息结尾的信号。

     public   class  SynchronousSocketListener
    {
        
//  存放接收數據 Incoming data from the client. 
         public   static   string  data  =   null ;
        
public   static   void  StartListening()
        {
            
//  暫存接收數據 Data buffer for incoming data. 
             byte [] bytes  =   new  Byte[ 1024 ];
            
//  建立本地端口  
            IPHostEntry ipHostInfo  =  Dns.GetHostEntry(Dns.GetHostName());
            IPAddress ipAddress 
=  ipHostInfo.AddressList[ 0 ];
            IPEndPoint localEndPoint 
=   new  IPEndPoint(ipAddress,  11000 );
            
//  建立socket 
            Socket listener  =   new  Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            
//  bind本地端口並偵聽連接 
             try
            {
                listener.Bind(localEndPoint);
                listener.Listen(
10 );
                
//  開始偵聽連接 
                 while  ( true )
                {
                    Console.WriteLine(
" Waiting for a connection... " );
                    
//  應用程序暫停,等待客戶端的連接
                    Socket handler  =  listener.Accept();
                    data 
=   null ;
                    
//  處理連接
                     while  ( true )
                    {
                        bytes 
=   new   byte [ 1024 ];
                        
int  bytesRec  =  handler.Receive(bytes);
                        data 
+=  Encoding.ASCII.GetString(bytes,  0 , bytesRec);
                        
if  (data.IndexOf( " <EOF> " >   - 1 )
                        {
                            
break ;
                        }
                    }
                    
//  顯示數據. 
                    Console.WriteLine( " Text received : {0} " , data);
                    
//  發送數據. 
                     byte [] msg  =  Encoding.ASCII.GetBytes(data);
                    handler.Send(msg);
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                }
            }
            
catch  (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            Console.WriteLine(
" Press ENTER to continue... " );
            Console.Read();
        }
        
public   static   int  Main(String[] args)
        {
            StartListening();
            
return   0 ;
        }
    }

客戶端示例:

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

     public   class  SynchronousSocketClient
    {
        
public   static   void  StartClient()
        {
            
// 存放接收數據 
             byte [] bytes  =   new   byte [ 1024 ];
            
// 連接遠程設備
             try
            {
                
// 建立遠程端口 
                IPHostEntry ipHostInfo  =  Dns.GetHostEntry(Dns.GetHostName());
                IPAddress ipAddress 
=  ipHostInfo.AddressList[ 0 ];
                IPEndPoint remoteEP 
=   new  IPEndPoint(ipAddress,  11000 );
                
// 建立socket
                Socket sender  =   new  Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
                
// 將socket連接到遠程端口
                 try
                {
                    sender.Connect(remoteEP);
                    Console.WriteLine(
" Socket connected to {0} " ,sender.RemoteEndPoint.ToString());
                    
// 將字符串轉化為字節數組
                     byte [] msg  =  Encoding.ASCII.GetBytes( " This is a test<EOF> " );
                    
// 發送數據
                     int  bytesSent  =  sender.Send(msg);
                    
// 接收數據
                     int  bytesRec  =  sender.Receive(bytes);
                    Console.WriteLine(
" Echoed test = {0} " , Encoding.ASCII.GetString(bytes,  0 , bytesRec));
                    
// 關閉socket. 
                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();
                }
                
catch  (ArgumentNullException ane)
                {
                    Console.WriteLine(
" ArgumentNullException : {0} " , ane.ToString());
                }
                
catch  (SocketException se)
                {
                    Console.WriteLine(
" SocketException : {0} " , se.ToString());
                }
                
catch  (Exception e)
                {
                    Console.WriteLine(
" Unexpected exception : {0} " , e.ToString());
                }
            }
            
catch  (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
        
public   static   int  Main(String[] args)
        {
            StartClient();
            
return   0 ;
        }

    }

 

參考文獻:1 .http://www.jb51.net/html/200703/85/8050.htm

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值