NET使⽤SuperSocket完成TCPIP通信
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)
tcp ip协议下载{
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+端⼝号。注意在命令结束要按回车哦,红⾊框的位置返回表⽰成功,你也可以⾃定义⾃⼰想要的返回值

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。