SuperSocket服务器架设(二):使用SuperSocket构建简单服务器

来源:互联网 发布:液流电池 知乎 编辑:程序博客网 时间:2024/05/28 18:43

服务器效果截图:

 

客户端效果截图:

 

1.      创建控制台项目,导入SuperSocket.Common、SuperSocket.SocketBase、SuperSocket.SocketEngine并添加好引用


2.      在控制台项目中添加Config文件夹及SuperSocket提供的log4net配置文件


3.      添加using引用

[csharp] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. using SuperSocket.Common;  
  2. using SuperSocket.SocketBase;  
  3. using SuperSocket.SocketEngine;  
  4. using SuperSocket.SocketBase.Protocol;  

4.      Main方法添加代码:

[csharp] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. var appServer = new AppServer();  
  2.   
  3. //服务器端口  
  4. int port = 2000;  
  5.   
  6. //设置服务监听端口  
  7. if (!appServer.Setup(port))  
  8. {  
  9.     Console.WriteLine("端口设置失败!");  
  10.     Console.ReadKey();  
  11.     return;  
  12. }  
  13.   
  14. //新连接事件  
  15. appServer.NewSessionConnected += new SessionHandler<AppSession>(NewSessionConnected);  
  16.   
  17. //收到消息事件  
  18. appServer.NewRequestReceived += new RequestHandler<AppSession, StringRequestInfo>(NewRequestReceived);  
  19.   
  20. //连接断开事件  
  21. appServer.SessionClosed += new SessionHandler<AppSession, CloseReason>(SessionClosed);  
  22.   
  23. //启动服务  
  24. if (!appServer.Start())  
  25. {  
  26.     Console.WriteLine("启动服务失败!");  
  27.     Console.ReadKey();  
  28.     return;  
  29. }  
  30.   
  31. Console.WriteLine("启动服务成功,输入exit退出!");  
  32.   
  33. while (true)  
  34. {  
  35.     var str = Console.ReadLine();  
  36.     if (str.ToLower().Equals("exit"))  
  37.     {  
  38.         break;  
  39.     }  
  40. }  
  41.   
  42. Console.WriteLine();  
  43.   
  44. //停止服务  
  45. appServer.Stop();  
  46.   
  47. Console.WriteLine("服务已停止,按任意键退出!");  
  48. Console.ReadKey();  

5.       添加事件对应方法

[csharp] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. static void NewSessionConnected(AppSession session)  
  2. {  
  3.     //向对应客户端发送数据  
  4.     session.Send("Hello User!");  
  5. }  
  6.   
  7. static void NewRequestReceived(AppSession session, StringRequestInfo requestInfo)  
  8. {  
  9.     /** 
  10.      * requestInfo为客户端发送的指令,默认为命令行协议 
  11.      * 例: 
  12.      * 发送 ping 127.0.0.1 -n 5 
  13.      * requestInfo.Key: "ping" 
  14.      * requestInfo.Body: "127.0.0.1 -n 5" 
  15.      * requestInfo.Parameters: ["127.0.0.1","-n","5"] 
  16.      **/  
  17.     switch (requestInfo.Key.ToUpper())  
  18.     {  
  19.         case ("HELLO"):  
  20.             session.Send("Hello World!");  
  21.             break;  
  22.   
  23.         default:  
  24.             session.Send("未知的指令。");  
  25.             break;  
  26.     }  
  27. }  
  28.   
  29. static void SessionClosed(AppSession session, CloseReason reason)  
  30. {   
  31.       
  32. }  

6.备注:

         (1).在SuperSocket.Base中,需要将引用中的log4net属性做如下修改:

         

         (2).客户端可以使用 telnet 地址 端口连接:

        

0 0
原创粉丝点击