在C#中使用異步Socket編程實現TCP網絡服務的C/S的通訊構架(二)----使用方法
一.TcpSvr的使用方法
A.測試程序:
using System;
using Ibms.Net.TcpCSFramework;
using System.Collections;
using System.Net.Sockets;
namespace Ibms.Test
{
/// <summary>
/// 測試TcpSvr的類
/// </summary>
public class TestTcpSvr
{
public TestTcpSvr()
{
}
public static void Main()
{
try
{
Console.WriteLine("Begin to Test TcpSvr class...");
TestTcpSvr tts = new TestTcpSvr();
//TcpSvr svr = new TcpSvr(9050,4);//默認使用Encoding.Default編碼方式
TcpSvr svr = new TcpSvr(9050,4,new Coder(Coder.EncodingMothord.UTF8));
svr.Resovlver = new DatagramResolver("##");
//定義服務器的4個事件
//服務器滿
svr.ServerFull += new NetEvent(tts.ServerFull);
//新客戶端連接
svr.ClientConn += new NetEvent(tts.ClientConn);
//客戶端關閉
svr.ClientClose += new NetEvent(tts.ClientClose);
//接收到數據
svr.RecvData += new NetEvent(tts.RecvData);
//命令控制循環
while(true)
{
Console.Write(">");
string cmd=Console.ReadLine();
//退出測試程序
if(cmd.ToLower() == "exit")
{
break;
}
//停止服務器程序
if(cmd.ToLower() == "stop")
{
svr.Stop();
Console.WriteLine("Server is Stop.");
continue;
}
//運行服務器程序
if(cmd.ToLower() == "start")
{
svr.Start();
Console.WriteLine("Server is listen...{0}",
svr.ServerSocket.LocalEndPoint.ToString());
continue;
}
//察看服務器在線客戶端數目和容量
if(cmd.ToLower() == "count")
{
Console.WriteLine("Current count of Client is {0}/{1}",
svr.SessionCount,svr.Capacity);
continue;
}
//發送數據到客戶端格式:send [Session] [stringData]
if(cmd.ToLower().IndexOf("send") !=-1)
{
cmd = cmd.ToLower();
string[] para = cmd.Split(' ');
if(para.Length ==3)
{
Session client = (Session)svr.SessionTable[ new SessionId( int.Parse
(para[1]))];
if(client !=null)
{
svr.Send(client, para[2]);
}
else
{
Console.WriteLine("The Session is Null");
}
}
else
{
Console.WriteLine("Error Command");
}
continue;
}
//從服務器上踢掉一個客戶端
if(cmd.ToLower().IndexOf("kick") !=-1)
{
cmd = cmd.ToLower();
string[] para = cmd.Split(' ');
if(para.Length ==2)
{
Session client = (Session)svr.SessionTable[ new SessionId( int.Parse
(para[1]))];
if(client !=null)
{
svr.CloseSession(client);
}
else
{
Console.WriteLine("The Session is Null");
}
}
else
{
Console.WriteLine("Error command");
}
continue;
}
//列出服務器上所有的客戶端信息
if(cmd.ToLower() == "list")
{
int i=0;
foreach( Session Client in svr.SessionTable.Values)
{
if(Client !=null)
{
i++;
string info = string.Format("{0} Client:{1} connected server Session:{2}. Socket Handle:{3}",
i,
Client.ClientSocket.RemoteEndPoint.ToString(),
Client.ID,
Client.ClientSocket.Handle);
Console.WriteLine( info );
}
else
{
i++;
string info = string.Format("{0} null Client", i);
Console.WriteLine(info);
}
}
continue;
}
Console.WriteLine("Unkown Command");
}//end of while
Console.WriteLine("End service");
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
void ClientConn(object sender, NetEventArgs e)
{
string info = string.Format("A Client:{0} connect server Session:{1}. Socket Handle:{2}",
e.Client.ClientSocket.RemoteEndPoint.ToString(),
e.Client.ID,e.Client.ClientSocket.Handle);
Console.WriteLine( info );
Console.Write(">");
}
void ServerFull(object sender, NetEventArgs e)
{
string info = string.Format("Server is full.the Client:{0} is refused",
e.Client.ClientSocket.RemoteEndPoint.ToString());
//Must do it
//服務器滿了,必須關閉新來的客戶端連接
e.Client.Close();
Console.WriteLine(info);
Console.Write(">");
}
void ClientClose(object sender, NetEventArgs e)
{
string info ;
if( e.Client.TypeOfExit == Session.ExitType.ExceptionExit)
{
info= string.Format("A Client Session:{0} Exception Closed.",
e.Client.ID);
}
else
{
info= string.Format("A Client Session:{0} Normal Closed.",
e.Client.ID);
}
Console.WriteLine( info );
Console.Write(">");
}
void RecvData(object sender, NetEventArgs e)
{
string info = string.Format("recv data:{0} from:{1}.",e.Client.Datagram, e.Client);
Console.WriteLine( info );
TcpSvr svr = (TcpSvr) sender;
//測試把收到的數據返回給客戶端
svr.Send(e.Client, e.Client.Datagram);
Console.Write(">");
}
}
}
B.說明:
使用命令來操作服務器
exit 退出
start 開始服務
kick 關閉客戶端
send 發送數據
list 列出所有客戶端的狀態
count 客戶端計數
先啓動服務運行start,等待客戶端連接。
然後可以使用list,count察看當前的連接狀況
每個事件都有相應函數,客戶就在事件處理函數中處理自己的業務邏輯
可以通過繼承特化自己的服務器應用,基本的框架不變
二.TcpCli的使用方法
A.測試程序:
using System;
using Ibms.Net.TcpCSFramework;
namespace Ibms.Test
{
/// <summary>
/// TestTcpClient 的摘要說明。
/// </summary>
public class TestTcpClient
{
public TestTcpClient()
{
//
// TODO: 在此處添加構造函數邏輯
//
}
public static void Test()
{
Console.WriteLine("Begin to Test TcpCli Class..");
TestTcpClient test = new TestTcpClient();
TcpCli cli = new TcpCli( new Coder(Coder.EncodingMothord.UTF8));
cli.Resovlver = new DatagramResolver("##");
cli.ReceivedDatagram += new NetEvent(test.RecvData);
cli.DisConnectedServer += new NetEvent(test.ClientClose);
cli.ConnectedServer += new NetEvent(test.ClientConn);
try
{
//命令控制循環
while(true)
{
Console.Write(">");
string cmd=Console.ReadLine();
if(cmd.ToLower() == "exit")
{
break;
}
if(cmd.ToLower() == "close")
{
cli.Close();
continue;
}
if(cmd.ToLower().IndexOf("conn")!=-1)
{
cmd = cmd.ToLower();
string[] para = cmd.Split(' ');
if(para.Length ==3)
{
cli.Connect(para[1],int.Parse(para[2]));
}
else
{
Console.WriteLine("Error Command");
}
continue;
}
if(cmd.ToLower().IndexOf("send") !=-1)
{
cmd = cmd.ToLower();
string[] para = cmd.Split(' ');
if(para.Length ==2)
{
cli.Send(para[1]);
}
else
{
Console.WriteLine("Error Command");
}
continue;
}
Console.WriteLine("Unkown Command");
}//end of while
Console.WriteLine("End service");
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
void ClientConn(object sender, NetEventArgs e)
{
string info = string.Format("A Client:{0} connect server :{1}",e.Client,
e.Client.ClientSocket.RemoteEndPoint.ToString());
Console.WriteLine( info );
Console.Write(">");
}
void ClientClose(object sender, NetEventArgs e)
{
string info ;
if( e.Client.TypeOfExit == Session.ExitType.ExceptionExit)
{
info= string.Format("A Client Session:{0} Exception Closed.",
e.Client.ID);
}
else
{
info= string.Format("A Client Session:{0} Normal Closed.",
e.Client.ID);
}
Console.WriteLine( info );
Console.Write(">");
}
void RecvData(object sender, NetEventArgs e)
{
string info = string.Format("recv data:{0} from:{1}.",e.Client.Datagram, e.Client);
Console.WriteLine( info );
Console.Write(">");
}
}
}
B.說明:
先建立連接,Conn 192.9.207.214 9050
然後可以Send 數據
最後關閉連接Close
三.編碼器
如果你要加密你的報文,需要一個你自己的Coder
從Coder類繼承一個如MyCoder類,然後重載編碼和解碼函數。
使用方法:
TcpCli cli = new TcpCli( new MyCoder());
就可以在客戶端使用該編碼器了。
四.報文解析器
與編碼器同樣的實現方法。