socket异步通讯 客户端

ExpandedBlockStart.gif 代码
using  System;
using  System.Collections.Generic;
using  System.Linq;
using  System.Text;
using  System.Net.Sockets;
using  System.Net;
namespace  ConsoleApplication4
{
    
class  Program
    {
       
public   class  SocketAsyncClient   
    {   
        
// -------属性开始   
         ///   <summary>    
        
///  发送/接收套节字   
        
///   </summary>    
         private  Socket SendSocket;   
  
        
///   <summary>    
        
///  网络端点( IP 地址和端口号)   
        
///   </summary>    
         private  IPEndPoint hostEndPoint;   
  
        
///   <summary>    
        
///  异步对象上下文   
        
///   </summary>    
         private  SocketAsyncEventArgs SendEventArg;   
  
        
///   <summary>    
        
///  到回发消息委托   
        
///   </summary>    
        
///   <param name="msg"> 回发消息 </param>    
         public   delegate   void  ReceiveMSGHandler( string  msg);   
  
        
///   <summary>    
        
///  到回发消息事件   
        
///   </summary>    
         public   event  ReceiveMSGHandler ReceiveMSGEvent;   
  
        
// -------属性结束   
  
  
        
internal  SocketAsyncClient( string  ip, Int32 port)   
        {   
            
this .hostEndPoint  =   new  IPEndPoint(IPAddress.Parse(ip), port);   
            
this .SendSocket  =   new  Socket( this .hostEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);   
            
this .SendSocket.Connect(hostEndPoint);   
        }


        
public   void  Init()
        {
            SendEventArg 
=   new  SocketAsyncEventArgs();
            Byte[] sendBuffer 
=  Encoding.UTF8.GetBytes( " jklk " );

            SendEventArg.SetBuffer(sendBuffer, 
0 , sendBuffer.Length);   
            SendEventArg.UserToken 
=   this .SendSocket;
            SendEventArg.RemoteEndPoint 
=   this .hostEndPoint;
         
            SendEventArg.Completed 
+=   new  EventHandler < SocketAsyncEventArgs > (OnReceiveCompleted);

            Boolean willRaiseEvent 
=   this .SendSocket.ReceiveAsync(SendEventArg);  
         
        }
  
        
///   <summary>    
        
///  发送消息   
        
///   </summary>    
        
///   <param name="msg"> 消息 </param>    
         public   void  SendMsg( string  msg)   
        {   
            
if  (SendEventArg  ==   null )   
            {   
                SendEventArg 
=   new  SocketAsyncEventArgs();   
                
// 发送缓存   
                Byte[] sendBuffer  =  Encoding.UTF8.GetBytes(msg);   
  
                SendEventArg.SetBuffer(sendBuffer, 
0 , sendBuffer.Length);   
                SendEventArg.UserToken 
=   this .SendSocket;   
                SendEventArg.RemoteEndPoint 
=   this .hostEndPoint;   
                
// 异步接收请求回调
                SendEventArg.Completed  +=   new  EventHandler < SocketAsyncEventArgs > (OnSendCompleted);   
            }   
            
else   
            {   
                
// 重用异步对象上下文时消除其socket   
                SendEventArg.AcceptSocket  =   null ;   
            }   
  
  
            
// 开始异步发送   
            Boolean willRaiseEvent  =   this .SendSocket.SendAsync(SendEventArg);   

  
            
// 同步完成   
             if  ( ! willRaiseEvent)   
            {   
                
this .OnSendCompleted( null , SendEventArg);   
            }   
        }   
  
        
///   <summary>    
        
///  发送完成回调   
        
///   </summary>    
        
///   <param name="sender"></param>    
        
///   <param name="e"> 异步对象上下文 </param>    
         private   void  OnSendCompleted( object  sender, SocketAsyncEventArgs e)   
        {   
            
if  (e.SocketError  ==  SocketError.Success)   
            {   
                
if  (e.LastOperation  ==  SocketAsyncOperation.Send)   
                {   
                    
//  准备接收   
                    Socket s  =  e.UserToken  as  Socket;   
  
                    
// 接收缓存   
                     byte [] receiveBuffer  =   new   byte [ 255 ];   
                    e.SetBuffer(receiveBuffer, 
0 , receiveBuffer.Length);   
                    
// 接收完成回调   
                    e.Completed  +=   new  EventHandler < SocketAsyncEventArgs > (OnReceiveCompleted);   
                    
// 开始异步接收   
                    Boolean willRaiseEvent  =  s.ReceiveAsync(e);   
                    
if  ( ! willRaiseEvent)   
                    {   
                        
this .OnReceiveCompleted( null , e);   
                    }   
                }   
            }   
            
else   
            {   
                
this .CloseClientSocket(e);   
            }   
        }   
  
        
///   <summary>    
        
///  接收完成回调   
        
///   </summary>    
        
///   <param name="sender"></param>    
        
///   <param name="e"> 异步对象上下文 </param>    
         private   void  OnReceiveCompleted( object  sender, SocketAsyncEventArgs e)   
        {   
            
//  检查远程主机是否断开   
             if  (e.BytesTransferred  >   0   &&  e.SocketError  ==  SocketError.Success)   
            {   
                Socket s 
=  e.UserToken  as  Socket;   
  
                Int32 bytesTransferred 
=  e.BytesTransferred;   
  
                
//  Get the message received from the listener.   
                String received  =  Encoding.UTF8.GetString(e.Buffer, e.Offset, bytesTransferred);   
  
                
// 得到回发消息事件   
                ReceiveMSGEvent(received);   
            }   
            
else   
            {   
                
this .CloseClientSocket(e);   
            }   
        }   
  
        
///   <summary>    
        
///  关闭socket   
        
///   </summary>    
        
///   <param name="e"> 异步对象上下文 </param>    
         private   void  CloseClientSocket(SocketAsyncEventArgs e)   
        {   
            Socket s 
=  e.UserToken  as  Socket;   
  
            
try   
            {   
                s.Shutdown(SocketShutdown.Send);   
            }   
  
            
catch  (Exception ex)   
            {   
                s.Close();   
                
throw  ex;   
            }   
            s.Close();   
        }   
    }    
        
static    void   GetReceiveMSG( string  msg)
            {   
                  Console.WriteLine(msg);
                  
              

             }
        
static   void  Main( string [] args)
        {
          
            SocketAsyncClient sac 
=   new  SocketAsyncClient( " 127.0.0.1 " 9050 );
            sac.ReceiveMSGEvent 
+=  GetReceiveMSG;   
      
            
while  ( true )
            {
              
                Console.WriteLine(
" 请选择你的模式,1 等待接收模式 2 客户端发送模式 3退出 " );   string  flag  =  Console.ReadLine();
                
switch  (flag)
                {
                    
case   " 1 " : sac.Init();  break ;
                    
case   " 2 " :    
                        sac.ReceiveMSGEvent 
+=  GetReceiveMSG;
                         Console.WriteLine(
" 请输入你要发送的内容 " );
                           
string  content =   Console.ReadLine();

                        sac.SendMsg(content);
break ;
                    
case   " 3 " return ;
                }
            }
         
           
      
            
   
          
         }
     
///   <summary>    
    
///  异步“发送--接收”Socket类。
    
///   </summary>    
   




    }
}

 

转载于:https://www.cnblogs.com/longfeitengda/archive/2010/05/28/1746473.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值