/// <summary>
/// 提供Tcp網絡連接服務的客戶端類
///
/// 版本: 1.0
/// 替換版本:
///
/// 特征:
/// 原理:
/// 1.使用異步Socket通訊與服務器按照一定的通訊格式通訊,請注意與服務器的通
/// 訊格式一定要一致,否則可能造成服務器程序崩潰,整個問題沒有克服,怎麼從byte[]
/// 判斷它的編碼格式
/// 2.支持帶標記的數據報文格式的識別,以完成大數據報文的傳輸和適應惡劣的網
/// 絡環境.
/// 用法:
/// 注意:
/// </summary>
public class TcpCli
{
#region 字段
/// <summary>
/// 客戶端與服務器之間的會話類
/// </summary>
private Session _session;
/// <summary>
/// 客戶端是否已經連接服務器
/// </summary>
private bool _isConnected = false;
/// <summary>
/// 接收數據緩沖區大小64K
/// </summary>
public const int DefaultBufferSize = 64*1024;
/// <summary>
/// 報文解析器
/// </summary>
private DatagramResolver _resolver;
/// <summary>
/// 通訊格式編碼解碼器
/// </summary>
private Coder _coder;
/// <summary>
/// 接收數據緩沖區
/// </summary>
private byte[] _recvDataBuffer = new byte[DefaultBufferSize];
#endregion
#region 事件定義
//需要訂閱事件才能收到事件的通知,如果訂閱者退出,必須取消訂閱
/// <summary>
/// 已經連接服務器事件
/// </summary>
public event NetEvent ConnectedServer;
/// <summary>
/// 接收到數據報文事件
/// </summary>
public event NetEvent ReceivedDatagram;
/// <summary>
/// 連接斷開事件
/// </summary>
public event NetEvent DisConnectedServer;
#endregion
#region 屬性
/// <summary>
/// 返回客戶端與服務器之間的會話對象
/// </summary>
public Session ClientSession
{
get
{
return _session;
}
}
/// <summary>
/// 返回客戶端與服務器之間的連接狀態
/// </summary>
public bool IsConnected
{
get
{
return _isConnected;
}
}
/// <summary>
/// 數據報文分析器
/// </summary>
public DatagramResolver Resovlver
{
get
{
return _resolver;
}
set
{
_resolver = value;
}
}
/// <summary>
/// 編碼解碼器
/// </summary>
public Coder ServerCoder
{
get
{
return _coder;
}
}
#endregion
#region 公有方法
/// <summary>
/// 默認構造函數,使用默認的編碼格式
/// </summary>
public TcpCli()
{
_coder = new Coder( Coder.EncodingMothord.Default );
}
/// <summary>
/// 構造函數,使用一個特定的編碼器來初始化
/// </summary>
/// <param name="_coder">報文編碼器</param>
public TcpCli( Coder coder )
{
_coder = coder;
}
/// <summary>
/// 連接服務器
/// </summary>
/// <param name="ip">服務器IP地址</param>
/// <param name="port">服務器端口</param>
public virtual void Connect( string ip, int port)
{
if(IsConnected)
{
//重新連接
Debug.Assert( _session !=null);
Close();
}
Socket newsock= new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint iep = new IPEndPoint( IPAddress.Parse(ip), port);
newsock.BeginConnect(iep, new AsyncCallback(Connected), newsock);
}
/// <summary>
/// 發送數據報文
/// </summary>
/// <param name="datagram"></param>
public virtual void Send( string datagram)
{
if(datagram.Length ==0 )
{
return;
}
if( !_isConnected )
{
throw (new ApplicationException("沒有連接服務器,不能發送數據") );
}
//獲得報文的編碼字節
byte [] data = _coder.GetEncodingBytes(datagram);
_session.ClientSocket.BeginSend( data, 0, data.Length, SocketFlags.None,
new AsyncCallback( SendDataEnd ), _session.ClientSocket);
}
/// <summary>
/// 關閉連接
/// </summary>
public virtual void Close()
{
if(!_isConnected)
{
return;
}
_session.Close();
_session = null;
_isConnected = false;
}
#endregion
#region 受保護方法
/// <summary>
/// 數據發送完成處理函數
/// </summary>
/// <param name="iar"></param>
protected virtual void SendDataEnd(IAsyncResult iar)
{
Socket remote = (Socket)iar.AsyncState;
int sent = remote.EndSend(iar);
Debug.Assert(sent !=0);
}
/// <summary>
/// 建立Tcp連接後處理過程
/// </summary>
/// <param name="iar">異步Socket</param>
protected virtual void Connected(IAsyncResult iar)
{
Socket socket = (Socket)iar.AsyncState;
socket.EndConnect(iar);
//創建新的會話
_session = new Session(socket);
_isConnected = true;
//觸發連接建立事件
if(ConnectedServer != null)
{
ConnectedServer(this, new NetEventArgs(_session));
}
//建立連接後應該立即接收數據
_session.ClientSocket.BeginReceive(_recvDataBuffer, 0,
DefaultBufferSize, SocketFlags.None,
new AsyncCallback(RecvData), socket);
}
/// <summary>
/// 數據接收處理函數
/// </summary>
/// <param name="iar">異步Socket</param>
protected virtual void RecvData(IAsyncResult iar)
{
Socket remote = (Socket)iar.AsyncState;
try
{
int recv = remote.EndReceive(iar);
//正常的退出
if(recv ==0 )
{
_session.TypeOfExit = Session.ExitType.NormalExit;
if(DisConnectedServer!=null)
{
DisConnectedServer(this, new NetEventArgs(_session));
}
return;
}
string receivedData = _coder.GetEncodingString( _recvDataBuffer,recv );
//通過事件發布收到的報文
if(ReceivedDatagram != null)
{
//通過報文解析器分析出報文
//如果定義了報文的尾標記,需要處理報文的多種情況
if(_resolver != null)
{
if( _session.Datagram !=null &&
_session.Datagram.Length !=0)
{
//加上最後一次通訊剩余的報文片斷
receivedData= _session.Datagram + receivedData ;
}
string [] recvDatagrams = _resolver.Resolve(ref receivedData);
foreach(string newDatagram in recvDatagrams)
{
//Need Deep Copy.因為需要保證多個不同報文獨立存在
ICloneable copySession = (ICloneable)_session;
Session clientSession = (Session)copySession.Clone();
clientSession.Datagram = newDatagram;
//發布一個報文消息
ReceivedDatagram(this,new NetEventArgs( clientSession ));
}
//剩余的代碼片斷,下次接收的時候使用
_session.Datagram = receivedData;
}
//沒有定義報文的尾標記,直接交給消息訂閱者使用
else
{
ICloneable copySession = (ICloneable)_session;
Session clientSession = (Session)copySession.Clone();
clientSession.Datagram = receivedData;
ReceivedDatagram( this, new NetEventArgs( clientSession ));
}
}//end of if(ReceivedDatagram != null)
//繼續接收數據
_session.ClientSocket.BeginReceive(_recvDataBuffer, 0, DefaultBufferSize, SocketFlags.None,
new AsyncCallback(RecvData), _session.ClientSocket);
}
catch(SocketException ex)
{
//客戶端退出
if( 10054 == ex.ErrorCode )
{
//服務器強制的關閉連接,強制退出
_session.TypeOfExit = Session.ExitType.ExceptionExit;
if(DisConnectedServer!=null)
{
DisConnectedServer(this, new NetEventArgs(_session));
}
}
else
{
throw( ex );
}
}
catch(ObjectDisposedException ex)
{
//這裡的實現不夠優雅
//當調用CloseSession()時,會結束數據接收,但是數據接收
//處理中會調用int recv = client.EndReceive(iar);
//就訪問了CloseSession()已經處置的對象
//我想這樣的實現方法也是無傷大雅的.
if(ex!=null)
{
ex =null;
//DoNothing;
}
}
}
#endregion
}
/// <summary>
/// 通訊編碼格式提供者,為通訊服務提供編碼和解碼服務
/// 你可以在繼承類中定制自己的編碼方式如:數據加密傳輸等
/// </summary>
public class Coder
{
/// <summary>
/// 編碼方式
/// </summary>
private EncodingMothord _encodingMothord;
protected Coder()
{
}
public Coder(EncodingMothord encodingMothord)
{
_encodingMothord = encodingMothord;
}
public enum EncodingMothord
{
Default =0,
Unicode,
UTF8,
ASCII,
}
/// <summary>
/// 通訊數據解碼
/// </summary>
/// <param name="dataBytes">需要解碼的數據</param>
/// <returns>編碼後的數據</returns>
public virtual string GetEncodingString( byte [] dataBytes,int size)
{
switch( _encodingMothord )
{
case EncodingMothord.Default:
{
return Encoding.Default.GetString(dataBytes,0,size);
}
case EncodingMothord.Unicode:
{
return Encoding.Unicode.GetString(dataBytes,0,size);
}
case EncodingMothord.UTF8:
{
return Encoding.UTF8.GetString(dataBytes,0,size);
}
case EncodingMothord.ASCII:
{
return Encoding.ASCII.GetString(dataBytes,0,size);
}
default:
{
throw( new Exception("未定義的編碼格式"));
}
}
}
/// <summary>
/// 數據編碼
/// </summary>
/// <param name="datagram">需要編碼的報文</param>
/// <returns>編碼後的數據</returns>
public virtual byte[] GetEncodingBytes(string datagram)
{
switch( _encodingMothord)
{
case EncodingMothord.Default:
{
return Encoding.Default.GetBytes(datagram);
}
case EncodingMothord.Unicode:
{
return Encoding.Unicode.GetBytes(datagram);
}
case EncodingMothord.UTF8:
{
return Encoding.UTF8.GetBytes(datagram);
}
case EncodingMothord.ASCII:
{
return Encoding.ASCII.GetBytes(datagram);
}
default:
{
throw( new Exception("未定義的編碼格式"));
}
}
}
}
/// <summary>
/// 數據報文分析器,通過分析接收到的原始數據,得到完整的數據報文.
/// 繼承該類可以實現自己的報文解析方法.
/// 通常的報文識別方法包括:固定長度,長度標記,標記符等方法
/// 本類的現實的是標記符的方法,你可以在繼承類中實現其他的方法
/// </summary>
public class DatagramResolver
{
/// <summary>
/// 報文結束標記
/// </summary>
private string endTag;
/// <summary>
/// 返回結束標記
/// </summary>
string EndTag
{
get
{
return endTag;
}
}
/// <summary>
/// 受保護的默認構造函數,提供給繼承類使用
/// </summary>
protected DatagramResolver()
{
}
/// <summary>
/// 構造函數
/// </summary>
/// <param name="endTag">報文結束標記</param>
public DatagramResolver(string endTag)
{
if(endTag == null)
{
throw (new ArgumentNullException("結束標記不能為null"));
}
if(endTag == "")
{
throw (new ArgumentException("結束標記符號不能為空字符串"));
}
this.endTag = endTag;
}
/// <summary>
/// 解析報文
/// </summary>
/// <param name="rawDatagram">原始數據,返回未使用的報文片斷,
/// 該片斷會保存在Session的Datagram對象中</param>
/// <returns>報文數組,原始數據可能包含多個報文</returns>
public virtual string [] Resolve(ref string rawDatagram)
{
ArrayList datagrams = new ArrayList();
//末尾標記位置索引 www.2cto.com
int tagIndex =-1;
while(true)
{
tagIndex = rawDatagram.IndexOf(endTag,tagIndex+1);
if( tagIndex == -1 )
{
break;
}
else
{
//按照末尾標記把字符串分為左右兩個部分
string newDatagram = rawDatagram.Substring(
0, tagIndex+endTag.Length);
datagrams.Add(newDatagram);
if(tagIndex+endTag.Length >= rawDatagram.Length)
{
rawDatagram="";
break;
}
rawDatagram = rawDatagram.Substring(tagIndex+endTag.Length,
rawDatagram.Length - newDatagram.Length);
//從開始位置開始查找
tagIndex=0;
}
}
string [] results= new string[datagrams.Count];
datagrams.CopyTo(results);
return results;
}
}
/// <summary>
/// 客戶端與服務器之間的會話類
///
/// 版本: 1.1
/// 替換版本: 1.0
///
/// 說明:
/// 會話類包含遠程通訊端的狀態,這些狀態包括Socket,報文內容,
/// 客戶端退出的類型(正常關閉,強制退出兩種類型)
/// </summary>
public class Session:ICloneable
{
#region 字段
/// <summary>
/// 會話ID
/// </summary>
private SessionId _id;
/// <summary>
/// 客戶端發送到服務器的報文
/// 注意:在有些情況下報文可能只是報文的片斷而不完整
/// </summary>
private string _datagram;
/// <summary>
/// 客戶端的Socket
/// </summary>
private Socket _cliSock;
/// <summary>
/// 客戶端的退出類型
/// </summary>
private ExitType _exitType;
/// <summary>
/// 退出類型枚舉
/// </summary>
public enum ExitType
{
NormalExit ,
ExceptionExit
};
#endregion
#region 屬性
/// <summary>
/// 返回會話的ID
/// </summary>
public SessionId ID
{
get
{
return _id;
}
}
/// <summary>
/// 存取會話的報文
/// </summary>
public string Datagram
{
get
{
return _datagram;
}
set
{
_datagram = value;
}
}
/// <summary>
/// 獲得與客戶端會話關聯的Socket對象
/// </summary>
public Socket ClientSocket
{
get
{
return _cliSock;
}
}
/// <summary>
/// 存取客戶端的退出方式
/// </summary>
public ExitType TypeOfExit
{
get
{
return _exitType;
}
set
{
_exitType = value;
}
}
#endregion
#region 方法
/// <summary>
/// 使用Socket對象的Handle值作為HashCode,它具有良好的線性特征.
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return (int)_cliSock.Handle;
}
/// <summary>
/// 返回兩個Session是否代表同一個客戶端
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
Session rightObj = (Session)obj;
return (int)_cliSock.Handle == (int)rightObj.ClientSocket.Handle;
}
/// <summary>
/// 重載ToString()方法,返回Session對象的特征
/// </summary>
/// <returns></returns>
public override string ToString()
{
string result = string.Format("Session:{0},IP:{1}",
_id,_cliSock.RemoteEndPoint.ToString());
//result.C
return result;
}
/// <summary>
/// 構造函數
/// </summary>
/// <param name="cliSock">會話使用的Socket連接</param>
public Session( Socket cliSock)
{
Debug.Assert( cliSock !=null );
_cliSock = cliSock;
_id = new SessionId( (int)cliSock.Handle);
}
/// <summary>
/// 關閉會話
/// </summary>
public void Close()
{
Debug.Assert( _cliSock !=null );
//關閉數據的接受和發送
_cliSock.Shutdown( SocketShutdown.Both );
//清理資源
_cliSock.Close();
}
#endregion
#region ICloneable 成員
object System.ICloneable.Clone()
{
Session newSession = new Session(_cliSock);
newSession.Datagram = _datagram;
newSession.TypeOfExit = _exitType;
return newSession;
}
#endregion
}
/// <summary>
/// 唯一的標志一個Session,輔助Session對象在Hash表中完成特定功能
/// </summary>
public class SessionId
{
/// <summary>
/// 與Session對象的Socket對象的Handle值相同,必須用這個值來初始化它
/// </summary>
private int _id;
/// <summary>
/// 返回ID值
/// </summary>
public int ID
{
get
{
return _id;
}
}
/// <summary>
/// 構造函數
/// </summary>
/// <param name="id">Socket的Handle值</param>
public SessionId(int id)
{
_id = id;
}
/// <summary>
/// 重載.為了符合Hashtable鍵值特征
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
if(obj != null )
{
SessionId right = (SessionId) obj;
return _id == right._id;
}
else if(this == null)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 重載.為了符合Hashtable鍵值特征
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return _id;
}
/// <summary>
/// 重載,為了方便顯示輸出
/// </summary>
/// <returns></returns>
public override string ToString()
{
return _id.ToString ();
}
}
/// <summary>
/// 服務器程序的事件參數,包含了激發該事件的會話對象
/// </summary>
public class NetEventArgs:EventArgs
{
#region 字段
/// <summary>
/// 客戶端與服務器之間的會話
/// </summary>
private Session _client;
#endregion
#region 構造函數
/// <summary>
/// 構造函數
/// </summary>
/// <param name="client">客戶端會話</param>
public NetEventArgs(Session client)
{
if( null == client)
{
throw(new ArgumentNullException());
}
_client = client;
}
#endregion
#region 屬性
/// <summary>
/// 獲得激發該事件的會話對象
/// </summary>
public Session Client
{
get
{
return _client;
}
}
#endregion
}
}
摘自 roosf的專欄