主题:使用SuperSocket实现简单的Telnet服务器
1.创建.net控制台项目。
2.打开NUGET包管理器安装SuperSocket、SuperSocket.Engine、System.Configuration.ConfigurationManager。
3.Program.cs
using System; using SuperSocket.SocketBase.Config; namespace TelnetDemo { class Program { /// <summary> /// SuperSocket服务启动或停止 /// </summary> /// <param name="args"></param> static void Main(string[] args) { Console.WriteLine("service"); //实例化服务器对象 SocketServer appServer = new SocketServer(); //appServer.NewSessionConnected += new AppSession(appServer_NewSessionConnected); var serverConfig = new ServerConfig(); //ip: 服务器监听的ip地址。你可以设置具体的地址,也可以设置为下面的值 Any serverConfig.Ip = "127.0.0.1"; serverConfig.Port = 8848; if (!appServer.Setup(serverConfig)) { Console.WriteLine("Failed to setup!"); return; } if (!appServer.Start()) { Console.WriteLine("Failed to start!"); return; } Console.WriteLine("ssssss前置机启动成功!,输入q关闭服务器"); while (Console.ReadKey().KeyChar != 'q') { continue; } appServer.Stop(); Console.WriteLine("服务器已经关闭"); Console.ReadKey(); } } }
4.创建AppSession扩展类。
using SuperSocket.SocketBase; using System; using System.Text; using SuperSocket.SocketBase.Protocol; namespace TelnetDemo { public class SocketSession : AppSession<SocketSession> { public override void Send(string message) { Console.WriteLine("发送消息:" + message); base.Send(message); } protected override void OnSessionStarted() { Console.WriteLine("Session已启动"); base.OnSessionStarted(); } protected override void OnInit() { this.Charset = Encoding.GetEncoding("utf-8"); base.OnInit(); } protected override void HandleUnknownRequest(StringRequestInfo requestInfo) { Console.WriteLine("遇到未知的请求"); base.HandleUnknownRequest(requestInfo); } } }
5.创建AppServer扩展类。
using SuperSocket.SocketBase; using System; namespace TelnetDemo { public class SocketServer : AppServer<SocketSession> { protected override void OnStarted() { Console.WriteLine("服务已开始"); base.OnStarted(); } protected override void OnStopped() { Console.WriteLine("服务已停止"); base.OnStopped(); } protected override void OnNewSessionConnected(SocketSession session) { Console.WriteLine("新的连接地址为" + session.LocalEndPoint.Address.ToString() + ",时间为" + DateTime.Now); base.OnNewSessionConnected(session); } } }
6.创建命令处理类。
using SuperSocket.SocketBase.Command; using SuperSocket.SocketBase.Protocol; using System; namespace TelnetDemo { public class AddItem_Command : CommandBase<SocketSession, StringRequestInfo> { public override void ExecuteCommand(SocketSession session, StringRequestInfo requestInfo) { if (requestInfo.Parameters.Length == 2) { Console.WriteLine("调用成功"); session.Send("已经成功接收到你的请求 "); } else { session.Send("参数不正确 "); } } public override string Name { get { return "AddItem"; } } } }