1)為什么使用SuperSocket?
性能高,易上手。有中文文檔,我們可以有更多的時間用在業務邏輯上,SuperSocket有效的利用自己的協議解決粘包
2)SuperSocket的協議內容?
命令 body 列如:TestCommand 1 2
3)怎樣在Net下使用 SuperSocket?
1)新建項目命名為SuperSocketWeb
2)引用程序集-》NuGet工具搜索安裝SuperSocket,SuperSocket.Engine兩個組件
3)下載測試工具SocketTool 官網demo存在
4)新建鏈接類 TestSession,每個鏈接為一個Session
using SuperSocket.SocketBase; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SuperSocket.SocketBase.Protocol; namespace SuperSocket { public class TestSession : AppSession<TestSession> { public int CustomID { get; set; } public string CustomName { get; set; } /// <summary> /// 用戶連接會話 /// </summary> protected override void OnSessionStarted() { Console.WriteLine("新的用戶請求"); base.OnSessionStarted(); } /// <summary> /// 未知的用戶請求命令 /// </summary> /// <param name="requestInfo"></param> protected override void HandleUnknownRequest(StringRequestInfo requestInfo) { base.HandleUnknownRequest(requestInfo); } /// <summary> /// 會話關閉 /// </summary> /// <param name="reason"></param> protected override void OnSessionClosed(CloseReason reason) { base.OnSessionClosed(reason); } } }
5)新建命令類TestCommand
using SuperSocket.SocketBase.Command; using SuperSocket.SocketBase.Protocol; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SuperSocket { public class TestCommand : CommandBase<TestSession, StringRequestInfo> { /// <summary> /// 命令處理類 /// </summary> /// <param name="session"></param> /// <param name="requestInfo"></param> public override void ExecuteCommand(TestSession session, StringRequestInfo requestInfo) { session.CustomID = new Random().Next(10000, 99999); session.CustomName = "hello word"; var key = requestInfo.Key; var param = requestInfo.Parameters; var body = requestInfo.Body; //返回隨機數session.Send(session.CustomID.ToString());
//返回
session.Send(body);
}
}
}
6)新建服務類 TestServer
using SuperSocket.SocketBase; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SuperSocket { public class TestServer : AppServer<TestSession> { } }
7)開啟tcp/ip監聽
在Global->Application_Start中開啟服務監聽,最好使用日志記錄監聽的開啟情況
var appServer = new TestServer(); if (!appServer.Setup(2012)) //開啟的監聽端口 { return; } if (!appServer.Start()) { return; }
4)測試demo
打開SocketTool,鏈接服務器ip+端口號。注意在命令結束要按回車哦,紅色框的位置
返回表示成功,你也可以自定義自己想要的返回值