1、预期效果如下图。
2、自定义AppServer,代码如下。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Config;namespace ConsoleApp1.Config
{/// <summary>/// 重写AppServer类/// </summary>public class SocketServer:AppServer<SocketSession>{/// <summary>/// 重写启动SocketServer/// </summary>/// <param name="rootConfig"></param>/// <param name="config"></param>/// <returns></returns>protected override bool Setup(IRootConfig rootConfig, IServerConfig config){Console.WriteLine("启动SocketServer");return base.Setup(rootConfig, config);}/// <summary>/// 重写服务已启动/// </summary>protected override void OnStarted(){Console.WriteLine("服务已开始");base.OnStarted();}/// <summary>/// 重写服务已停止/// </summary>protected override void OnStopped(){Console.WriteLine("服务已停止");base.OnStopped();}/// <summary>/// 重写新的连接建立/// </summary>/// <param name="session"></param>protected override void OnNewSessionConnected(SocketSession session){base.OnNewSessionConnected(session);Console.WriteLine("新客户端接入,IP地址为:"+session.RemoteEndPoint.Address.ToString());session.Send("Welcome");}/// <summary>/// 重写客户端连接关闭/// </summary>/// <param name="session"></param>/// <param name="reason"></param>protected override void OnSessionClosed(SocketSession session, CloseReason reason){base.OnSessionClosed(session, reason);Console.WriteLine("客户端断开,IP地址为:" + session.RemoteEndPoint.Address.ToString());}}
}
3、自定义AppSession,代码如下。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Protocol;namespace ConsoleApp1.Config
{/// <summary>/// 自定义连接类SocketSession/// </summary>public class SocketSession:AppSession<SocketSession>{/// <summary>/// 重写发送/// </summary>/// <param name="message"></param>public override void Send(string message){Console.WriteLine("发送消息:"+message);base.Send(message);}/// <summary>/// 重写客户端建立连接/// </summary>protected override void OnSessionStarted(){Console.WriteLine("客户端IP地址:"+this.LocalEndPoint.Address.ToString());base.OnSessionStarted();}/// <summary>/// 重写客户端断开连接/// </summary>/// <param name="reason"></param>protected override void OnSessionClosed(CloseReason reason){base.OnSessionClosed(reason);}/// <summary>/// 重写未知请求/// </summary>/// <param name="requestInfo"></param>protected override void HandleUnknownRequest(StringRequestInfo requestInfo){Console.WriteLine("遇到位置请求Key:"+requestInfo.Key+" Body:"+requestInfo.Body);base.HandleUnknownRequest(requestInfo);}/// <summary>/// 重写捕获异常/// </summary>/// <param name="e"></param>protected override void HandleException(Exception e){Console.WriteLine("error:{0}",e.Message);this.Send("error:{0}", e.Message);base.HandleException(e);}}
}
4、自定义CommandBase,代码如下。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;namespace ConsoleApp1.Config
{/// <summary>/// 自定义SocketCommand1/// </summary>public class SocketCommand1 : CommandBase<SocketSession, StringRequestInfo>{public override void ExecuteCommand(SocketSession session, StringRequestInfo requestInfo){session.Send("1");}}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;namespace ConsoleApp1.Config
{/// <summary>/// 自定义Command1/// </summary>public class SocketCommand2 : CommandBase<SocketSession, StringRequestInfo>{public override void ExecuteCommand(SocketSession session, StringRequestInfo requestInfo){session.Send(string.Format("{0} {1}","1","123"));}}
}
5、主程序Program.cs,代码如下。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;//引入命名空间
using SuperSocket.Common;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Protocol;
using SuperSocket.SocketEngine;namespace ConsoleApp1
{class Program{static void Main(string[] args){Console.WriteLine("请输入Start开启服务器");while (!Console.ReadLine().Equals("Start")){Console.WriteLine();continue;}// 初始化Socket服务var bootstrap = BootstrapFactory.CreateBootstrap();if (!bootstrap.Initialize()){Console.WriteLine("初始化失败");Console.ReadKey();return;}var result = bootstrap.Start();Console.WriteLine("服务正在启动: {0}",result);if (result == StartResult.Failed){Console.WriteLine("服务启动失败");Console.ReadKey();return;}Console.WriteLine("服务器启动成功,请输入Stop停止服务器");while (!Console.ReadLine().Equals("Stop")){Console.WriteLine();continue;}//服务停止bootstrap.Stop();Console.WriteLine("服务停止");Console.ReadKey();}/// <summary>/// 客户端连接服务器事件/// </summary>/// <param name="session"></param>private static void AppServer_NewSessionConnected(AppSession session){Console.WriteLine("新客户端已连接IP地址为:" + session.RemoteEndPoint.Address.ToString());session.Send("Welcome");}/// <summary>/// 接收到客户端发送的数据/// </summary>/// <param name="session"></param>/// <param name="requestInfo"></param>private static void AppServer_NewRequestReceived(AppSession session, StringRequestInfo requestInfo){var key = requestInfo.Key;var body = requestInfo.Body;var parameters=requestInfo.Parameters;switch (key){case "1":Console.WriteLine("收到客户端信息1。");session.Send("Received:" + key.ToString());break;default:Console.WriteLine("收到key:"+key.ToString());Console.WriteLine("收到body:" + body.ToString());for (int i = 0; i < parameters.Length; i++){Console.WriteLine("收到parameters:" + parameters[i]);}session.Send("Received Key:" + key.ToString());session.Send("Received Body:" + body.ToString());for (int i = 0; i < parameters.Length; i++){session.Send("Received parameters:" + parameters[i]);}break;}}/// <summary>/// 客户端关闭/// </summary>/// <param name="session"></param>/// <param name="value"></param>private static void AppServer_SessionClosed(AppSession session, CloseReason value){Console.WriteLine("IP地址为:" + session.RemoteEndPoint.Address.ToString()+ "客户端已下线");}}
}
6、App.config配置如下。
<?xml version="1.0" encoding="utf-8" ?>
<configuration><configSections><!--log 日志记录--><section name="log4net" type="System.Configuration.IgnoreSectionHandler"/><!--SocketEngine--><section name="superSocket" type="SuperSocket.SocketEngine.Configuration.SocketServiceConfig, SuperSocket.SocketEngine"/></configSections><!--服务信息描述,在window服务模式下的名称标识--><appSettings><add key="ServiceName" value="ConsoleApp1"/><add key="ServiceDescription" value="bjxingch"/></appSettings><!--SuperSocket服务配置信息 serverType是项目的服务如我自定义的Socketserver--><superSocket><servers><server name="ConsoleApp1"textEncoding="gb2312"serverType="ConsoleApp1.Config.SocketServer,ConsoleApp1"ip="Any"port="2024"maxConnectionNumber="100"/><!--name:实例名称textEncoding:编码方式"gb2312","utf-8" 默认是aciiserverType:需要注意,否则无法启动Serverip:监听ipport:端口号maxConnectionNumber:最大连接数--></servers></superSocket><startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" /></startup>
</configuration>
7、项目结构如下图。
8、Demo下载路径如下
https://download.csdn.net/download/xingchengaiwei/89311253