C#使用非同步Socket實現TCP網路服務的CS的通訊構架(二)使用方法

來源:互聯網
上載者:User

一.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());

就可以在用戶端使用該編碼器了。
四.報文解析器
與編碼器同樣的實現方法。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.