step1.先加入库SuperSocket.Common.dll, SuperSocket.SocketBase.dll, SuperSocket.SocketEngine.dll,log4net.dll,System.Threading.dll。同时还需引入NET中的System.Configuration。如果要使用默认日志框架,需要复制Config文件夹
step2.代码实现
1 class PRogram 2 { 3 static void Main(string[] args) 4 { 5 Console.WriteLine("press any key to start the server"); 6 Console.ReadKey(); 7 Console.WriteLine(); 8 AppServer server = new AppServer(); 9 if (!server.Setup(8000))10 {11 Console.WriteLine("Failed to setup");12 Console.ReadKey();13 return;14 }15 16 server.NewsessionConnected += new SessionHandler<AppSession>(server_NewSessionConnected);17 server.NewRequestReceived += new RequestHandler<AppSession, SuperSocket.SocketBase.Protocol.StringRequestInfo>(server_NewRequestReceived);18 19 if (!server.Start())20 {21 Console.WriteLine("Failed to start");22 Console.ReadKey();23 return;24 }25 26 Console.WriteLine("The server started successfully, press key 'q' to stop it!");27 28 while (Console.ReadKey().KeyChar != 'q')29 {30 Console.WriteLine();31 continue;32 }33 Console.WriteLine();34 server.Stop();35 Console.WriteLine("The server was stopped!");36 }37 38 static void server_NewRequestReceived(AppSession session, SuperSocket.SocketBase.Protocol.StringRequestInfo requestInfo)39 {40 Console.WriteLine(requestInfo.Key + " " + requestInfo.Body);41 switch (requestInfo.Key.ToUpper())42 {43 case ("ECHO"):44 string r = requestInfo.Body;45 session.Send(r);46 Console.WriteLine(r);47 break;48 49 case ("ADD"):50 string r2= requestInfo.Parameters.Select(p => Convert.ToInt32(p)).Sum().ToString();51 session.Send(r2);52 Console.WriteLine(r2);53 break;54 55 case ("MULT"):56 57 var result = 1;58 59 foreach (var factor in requestInfo.Parameters.Select(p => Convert.ToInt32(p)))60 {61 result *= factor;62 }63 64 session.Send(result.ToString());65 Console.WriteLine(result);66 break;67 }68 }69 70 static void server_NewSessionConnected(AppSession session)71 {72 Console.WriteLine(session.SessionID + ":connect successed");73 }74 }
Step3.测试:代码测试:在window中运行里面输入telnet 127.0.0.1 8000 然后按回车就可以了
新闻热点
疑难解答