日期:2013-05-08  浏览次数:20470 次

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