在C#中使用异步Socket编程实现TCP网络服务的C/S的通讯构架(二)----使用方法

一.TcpSvr的使用方法
A.测试程序:

  1. using System;
  2. using Ibms.Net.TcpCSFramework;
  3. using System.Collections;
  4. using System.Net.Sockets;
  5. namespace Ibms.Test
  6. {
  7. /// <summary>
  8. /// 测试TcpSvr的类
  9. /// </summary>
  10. public class TestTcpSvr
  11. {
  12. public TestTcpSvr()
  13. {
  14. }
  15. public static void Main()
  16. {
  17. try
  18. {
  19. Console.WriteLine("Begin to Test TcpSvr class...");
  20. TestTcpSvr tts = new TestTcpSvr();
  21. //TcpSvr svr = new TcpSvr(9050,4);//默认使用Encoding.Default编码方式
  22. TcpSvr svr = new TcpSvr(9050,4,new Coder(Coder.EncodingMothord.UTF8));
  23. svr.Resovlver = new DatagramResolver("##");
  24. //定义服务器的4个事件
  25. //服务器满
  26. svr.ServerFull += new NetEvent(tts.ServerFull);
  27. //新客户端连接
  28. svr.ClientConn += new NetEvent(tts.ClientConn);
  29. //客户端关闭
  30. svr.ClientClose += new NetEvent(tts.ClientClose);
  31. //接收到数据
  32. svr.RecvData += new NetEvent(tts.RecvData);
  33. //命令控制循环
  34. while(true)
  35. {
  36. Console.Write(">");
  37. string cmd=Console.ReadLine();
  38. //退出测试程序
  39. if(cmd.ToLower() == "exit")
  40. {
  41. break;
  42. }
  43. //停止服务器程序
  44. if(cmd.ToLower() == "stop")
  45. {
  46. svr.Stop();
  47. Console.WriteLine("Server is Stop.");
  48. continue;
  49. }
  50. //运行服务器程序
  51. if(cmd.ToLower() == "start")
  52. {
  53. svr.Start();
  54. Console.WriteLine("Server is listen...{0}",
  55. svr.ServerSocket.LocalEndPoint.ToString());
  56. continue;
  57. }
  58. //察看服务器在线客户端数目和容量
  59. if(cmd.ToLower() == "count")
  60. {
  61. Console.WriteLine("Current count of Client is {0}/{1}",
  62. svr.SessionCount,svr.Capacity);
  63. continue;
  64. }
  65. //发送数据到客户端格式:send [Session] [stringData]
  66. if(cmd.ToLower().IndexOf("send") !=-1)
  67. {
  68. cmd = cmd.ToLower();
  69. string[] para = cmd.Split(' ');
  70. if(para.Length ==3)
  71. {
  72. Session client = (Session)svr.SessionTable[ new SessionId( int.Parse
  73. (para[1]))];
  74. if(client !=null)
  75. {
  76. svr.Send(client, para[2]);
  77. }
  78. else
  79. {
  80. Console.WriteLine("The Session is Null");
  81. }
  82. }
  83. else
  84. {
  85. Console.WriteLine("Error Command");
  86. }
  87. continue;
  88. }
  89. //从服务器上踢掉一个客户端
  90. if(cmd.ToLower().IndexOf("kick") !=-1)
  91. {
  92. cmd = cmd.ToLower();
  93. string[] para = cmd.Split(' ');
  94. if(para.Length ==2)
  95. {
  96. Session client = (Session)svr.SessionTable[ new SessionId( int.Parse
  97. (para[1]))];
  98. if(client !=null)
  99. {
  100. svr.CloseSession(client);
  101. }
  102. else
  103. {
  104. Console.WriteLine("The Session is Null");
  105. }
  106. }
  107. else
  108. {
  109. Console.WriteLine("Error command");
  110. }
  111. continue;
  112. }
  113. //列出服务器上所有的客户端信息
  114. if(cmd.ToLower() == "list")
  115. {
  116. int i=0;
  117. foreach( Session Client in svr.SessionTable.Values)
  118. {
  119. if(Client !=null)
  120. {
  121. i++;
  122. string info = string.Format("{0} Client:{1} connected server Session:{2}. Socket Handle:{3}",
  123. i,
  124. Client.ClientSocket.RemoteEndPoint.ToString(),
  125. Client.ID,
  126. Client.ClientSocket.Handle);
  127. Console.WriteLine( info );
  128. }
  129. else
  130. {
  131. i++;
  132. string info = string.Format("{0} null Client", i);
  133. Console.WriteLine(info);
  134. }
  135. }
  136. continue;
  137. }
  138. Console.WriteLine("Unkown Command");
  139. }//end of while
  140. Console.WriteLine("End service");
  141. }
  142. catch(Exception ex)
  143. {
  144. Console.WriteLine(ex.ToString());
  145. }
  146. }
  147. void ClientConn(object sender, NetEventArgs e)
  148. {
  149. string info = string.Format("A Client:{0} connect server Session:{1}. Socket Handle:{2}",
  150. e.Client.ClientSocket.RemoteEndPoint.ToString(),
  151. e.Client.ID,e.Client.ClientSocket.Handle);
  152. Console.WriteLine( info );
  153. Console.Write(">");
  154. }
  155. void ServerFull(object sender, NetEventArgs e)
  156. {
  157. string info = string.Format("Server is full.the Client:{0} is refused",
  158. e.Client.ClientSocket.RemoteEndPoint.ToString());
  159. //Must do it
  160. //服务器满了,必须关闭新来的客户端连接
  161. e.Client.Close();
  162. Console.WriteLine(info);
  163. Console.Write(">");
  164. }
  165. void ClientClose(object sender, NetEventArgs e)
  166. {
  167. string info ;
  168. if( e.Client.TypeOfExit == Session.ExitType.ExceptionExit)
  169. {
  170. info= string.Format("A Client Session:{0} Exception Closed.",
  171. e.Client.ID);
  172. }
  173. else
  174. {
  175. info= string.Format("A Client Session:{0} Normal Closed.",
  176. e.Client.ID);
  177. }
  178. Console.WriteLine( info );
  179. Console.Write(">");
  180. }
  181. void RecvData(object sender, NetEventArgs e)
  182. {
  183. string info = string.Format("recv data:{0} from:{1}.",e.Client.Datagram, e.Client);
  184. Console.WriteLine( info );
  185. TcpSvr svr = (TcpSvr) sender;
  186. //测试把收到的数据返回给客户端
  187. svr.Send(e.Client, e.Client.Datagram);
  188. Console.Write(">");
  189. }
  190. }
  191. }
  192. B.说明:
  193. 使用命令来操作服务器
  194. exit 退出
  195. start 开始服务
  196. kick 关闭客户端
  197. send 发送数据
  198. list 列出所有客户端的状态
  199. count 客户端计数
  200. 先启动服务运行start,等待客户端连接。
  201. 然后可以使用list,count察看当前的连接状况
  202. 每个事件都有相应函数,客户就在事件处理函数中处理自己的业务逻辑
  203. 可以通过继承特化自己的服务器应用,基本的框架不变
  204. 二.TcpCli的使用方法
  205. A.测试程序:
  206. using System;
  207. using Ibms.Net.TcpCSFramework;
  208. namespace Ibms.Test
  209. {
  210. /// <summary>
  211. /// TestTcpClient 的摘要说明。
  212. /// </summary>
  213. public class TestTcpClient
  214. {
  215. public TestTcpClient()
  216. {
  217. //
  218. // TODO: 在此处添加构造函数逻辑
  219. //
  220. }
  221. public static void Test()
  222. {
  223. Console.WriteLine("Begin to Test TcpCli Class..");
  224. TestTcpClient test = new TestTcpClient();
  225. TcpCli cli = new TcpCli( new Coder(Coder.EncodingMothord.UTF8));
  226. cli.Resovlver = new DatagramResolver("##");
  227. cli.ReceivedDatagram += new NetEvent(test.RecvData);
  228. cli.DisConnectedServer += new NetEvent(test.ClientClose);
  229. cli.ConnectedServer += new NetEvent(test.ClientConn);
  230. try
  231. {
  232. //命令控制循环
  233. while(true)
  234. {
  235. Console.Write(">");
  236. string cmd=Console.ReadLine();
  237. if(cmd.ToLower() == "exit")
  238. {
  239. break;
  240. }
  241. if(cmd.ToLower() == "close")
  242. {
  243. cli.Close();
  244. continue;
  245. }
  246. if(cmd.ToLower().IndexOf("conn")!=-1)
  247. {
  248. cmd = cmd.ToLower();
  249. string[] para = cmd.Split(' ');
  250. if(para.Length ==3)
  251. {
  252. cli.Connect(para[1],int.Parse(para[2]));
  253. }
  254. else
  255. {
  256. Console.WriteLine("Error Command");
  257. }
  258. continue;
  259. }
  260. if(cmd.ToLower().IndexOf("send") !=-1)
  261. {
  262. cmd = cmd.ToLower();
  263. string[] para = cmd.Split(' ');
  264. if(para.Length ==2)
  265. {
  266. cli.Send(para[1]);
  267. }
  268. else
  269. {
  270. Console.WriteLine("Error Command");
  271. }
  272. continue;
  273. }
  274. Console.WriteLine("Unkown Command");
  275. }//end of while
  276. Console.WriteLine("End service");
  277. }
  278. catch(Exception ex)
  279. {
  280. Console.WriteLine(ex.ToString());
  281. }
  282. }
  283. void ClientConn(object sender, NetEventArgs e)
  284. {
  285. string info = string.Format("A Client:{0} connect server :{1}",e.Client,
  286. e.Client.ClientSocket.RemoteEndPoint.ToString());
  287. Console.WriteLine( info );
  288. Console.Write(">");
  289. }
  290. void ClientClose(object sender, NetEventArgs e)
  291. {
  292. string info ;
  293. if( e.Client.TypeOfExit == Session.ExitType.ExceptionExit)
  294. {
  295. info= string.Format("A Client Session:{0} Exception Closed.",
  296. e.Client.ID);
  297. }
  298. else
  299. {
  300. info= string.Format("A Client Session:{0} Normal Closed.",
  301. e.Client.ID);
  302. }
  303. Console.WriteLine( info );
  304. Console.Write(">");
  305. }
  306. void RecvData(object sender, NetEventArgs e)
  307. {
  308. string info = string.Format("recv data:{0} from:{1}.",e.Client.Datagram, e.Client);
  309. Console.WriteLine( info );
  310. Console.Write(">");
  311. }
  312. }
  313. }

B.说明:
先建立连接,Conn 192.9.207.214 9050
然后可以Send 数据
最后关闭连接Close

三.编码器
如果你要加密你的报文,需要一个你自己的Coder
从Coder类继承一个如MyCoder类,然后重载编码和解码函数。
使用方法:

TcpCli cli = new TcpCli( new MyCoder());

就可以在客户端使用该编码器了。
四.报文解析器
与编码器同样的实现方法。

posted on 2010-10-06 14:48  Morris  阅读(437)  评论(0编辑  收藏  举报

导航