一、什么是SuperSocket
以下是作者的介绍
执行以下命令,获取SuperSocket项目
$ git clone https://github.com/kerryjiang/SuperSocket
二、项目结构
三、开发过程
1.新建一个控制台项目ConsoleApp
1.1引用相关项目
1.2从Solution Items中引进日志文件
1.3设置SuperSocket.SocketBase45的log4net文件属性设置为【复制到本地】
2.编写Main方法
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6 using SuperSocket.SocketBase;
7
8 namespace ConsoleApp
9 {
10 class Program
11 {
12 static void Main(string[] args)
13 {
14 var appServer = new AppServer();
15 int port = 8888;
16 if (!appServer.Setup(port))
17 {
18 Console.WriteLine("端口设置失败");
19 Console.ReadKey();
20 return;
21 }
22 //连接时
23 appServer.NewSessionConnected += appServer_NewSessionConnected;
24 //接收信息时
25 appServer.NewRequestReceived += appServer_NewRequestReceived;
26 //关闭服务时
27 appServer.SessionClosed += appServer_SessionClosed;
28 if (!appServer.Start())
29 {
30 Console.WriteLine("启动服务失败");
31 Console.ReadKey();
32 return;
33 }
34 Console.WriteLine("服务启动成功,输入q退出");
35
36 while (true)
37 {
38 var str = Console.ReadLine();
39 if (str.ToLower().Equals("q"))
40 {
41 break;
42 }
43 }
44 Console.WriteLine();
45 appServer.Stop();
46 Console.WriteLine("服务已停止,按任意键退出");
47 Console.ReadKey();
48 }
49
50 private static void appServer_NewSessionConnected(AppSession session)
51 {
52 session.Send("Hello World!");
53 }
54
55 static void appServer_NewRequestReceived(AppSession session, SuperSocket.SocketBase.Protocol.StringRequestInfo requestInfo)
56 {
57 switch (requestInfo.Key.ToLower())
58 {
59 case "1":
60 session.Send("You input 1");
61 break;
62 case "2":
63 session.Send("You input 2");
64 break;
65 default:
66 session.Send("Unknow ");
67 break;
68 }
69 }
70
71 static void appServer_SessionClosed(AppSession session, CloseReason value)
72 {
73 session.Send("服务已关闭");
74 }
75 }
76 }
77
3.运行项目,使用Telnet为客户端