上一篇文章我们使用原生的socket分别实现了服务器和客户端,
本篇文章使用SuperSocket来开发实现服务器,
之前也介绍了SuperSocket是一个轻量级, 跨平台而且可扩展的 .Net/Mono Socket 服务器程序框架。你无须了解如何使用 Socket, 如何维护 Socket 连接和 Socket 如何工作,但是你却可以使用 SuperSocket 很容易的开发出一款 Socket 服务器端软件,例如游戏服务器,GPS 服务器, 工业控制服务和数据采集服务器等等。
接下来开始我们的开发,首先我们需要安装SuperSocket相关程序包,我们新建一个项目开发SuperSocket服务器
然后打开NuGet程序包管理器,搜索SuperSocket ,下载安装SuperSocket和SuperSocket.Engine
下载安装完毕后,我们的项目中会自动引用了SuperSocke和log4net 相关程序集和配置文件
进入正题上代码,我们这里只用SuperSocket做服务器端,客户端使用SocketTool做测试
SocketTool
链接:https://pan.baidu.com/s/1ykEofUIZKE2yhe3mMyRbJw
提取码:m2nk
SuperSocket实现服务器:
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms; 10 using System.Net.Sockets; 11 using System.Net; 12 using System.Threading; 13 using SuperSocket; 14 using SuperSocket.SocketBase; 15 using SuperSocket.SocketBase.Protocol; 16 17 namespace SuperSocket 18 { 19 public partial class SuperSocketServer : Form 20 { 21 public SuperSocketServer() 22 { 23 InitializeComponent(); 24 } 25 26 private void SuperSocketServer_Load(object sender, EventArgs e) 27 { 28 //txt_ip.Text = "127.0.0.1"; 29 txt_port.Text = "3333"; 30 } 31 32 //AppServer 代表了监听客户端连接,承载TCP连接的服务器实例。理想情况下,我们可以通过AppServer实例获取任何你想要的客户端连接,服务器级别的操作和逻辑应该定义在此类之中。 33 AppServer appServer; 34 //缓冲字节数组 35 byte[] buffer = new byte[2048]; 36 37 string ipAddress_Connect; 38 string ipAddress_Close; 39 string ipAddress_Receive; 40 41 //存储session和对应ip端口号的泛型集合 42 Dictionary<string, AppSession> sessionList = new Dictionary<string, AppSession>(); 43 44 enum OperateType 45 { 46 47 Add = 1, //添加 48 Remove = 2 //移除 49 } 50 51 /// <summary> 52 /// 开启服务 53 /// </summary> 54 /// <param name="sender"></param> 55 /// <param name="e"></param> 56 private void btn_StartListen_Click(object sender, EventArgs e) 57 { 58 appServer = new AppServer(); 59 if (!appServer.Setup(int.Parse(txt_port.Text))) 60 { 61 SetMessage("Failed to Setup"); 62 return; 63 } 64 if (!appServer.Start()) 65 { 66 SetMessage("Failed to Start"); 67 return; 68 } 69 else 70 { 71 SetMessage("开启监听"); 72 } 73 //SuperSocket自定义了三个事件 ,连接事件,接收事件,关闭事件 74 appServer.NewSessionConnected += appServer_NewSessionConnected; 75 appServer.NewRequestReceived += appServer_NewRequestReceived; 76 appServer.SessionClosed += appServer_SessionClosed; 77 } 78 79 /// <summary> 80 /// 接收连接 81 /// </summary> 82 /// <param name="session"></param> 83 void appServer_NewSessionConnected(AppSession session) 84 { 85 //有新连接的时候,添加记录 session.LocalEndPoint属性获取当前session的ip和端口号 86 //AppSession 代表一个和客户端的逻辑连接,基于连接的操作应该定于在该类之中。你可以用该类的实例发送数据到客户端,接收客户端发送的数据或者关闭连接。 87 88 //获取远程客户端的ip端口号 89 ipAddress_Connect = session.RemoteEndPoint.ToString(); 90 ComboboxHandle(ipAddress_Connect, OperateType.Add); 91 sessionList.Add(ipAddress_Connect, session); 92 SetMessage(ipAddress_Connect + "已连接!"); 93 } 94 95