这是一个SuperSocket 简单示例,包括服务端和客户端。
一、首先使用NuGet安装SuperSocket和SuperSocket.Engine
二、实现IRequestInfo(数据包):
数据包格式:
包头4个字节,前2个字节是请求命令,后2个字节是正文长度
using SuperSocket.socketBase.Protocol; System; System.Collections.Generic; System.Linq; System.Text; System.Threading.Tasks; namespace SuperSocketServer { public class MyRequestInfo : IRequestInfo { public MyRequestInfo(byte[] header,byte[] bodyBuffer) { Key = ASCIIEncoding.ASCII.GetString(new byte[] { header[0],header[1] }); Data = bodyBuffer; } string Key { get; set; } byte[] Data { string Body { get { return Encoding.UTF8.GetString(Data); } } } }
三、实现FixedHeaderReceiveFilter(数据包解析):
SuperSocket.Facility.Protocol; class MyReceiveFilter : FixedHeaderReceiveFilter<MyRequestInfo> { public MyReceiveFilter() : base(4) { } protected override int GetBodyLengthFromHeader(int offset,1)">int length) { return BitConverter.ToInt16(byte[] { header[offset + 2],header[offset + 3] },0); } override MyRequestInfo ResolveRequestInfo(ArraySegment<byte> header,1)">byte[] bodyBuffer,1)">byte[] body = bodyBuffer.Skip(offset).Take(length).ToArray(); return new MyRequestInfo(header.Array,body); } } }
四、实现AppSession:
SuperSocket.socketBase; class MySession : AppSession<MySession,MyRequestInfo>public MySession() { } void OnSessionStarted() { } OnInit() { base.OnInit(); } HandleUnkNownRequest(MyRequestInfo requestInfo) { } HandleException(Exception e) { } OnSessionClosed(CloseReason reason) { .OnSessionClosed(reason); } } }
五、实现AppServer:
SuperSocket.socketBase.Config; System.Threading.Tasks; Utils; class MyServer : AppServer<MySession,1)">public MyServer() : base(new DefaultReceiveFilterFactory<MyReceiveFilter,1)">()) { this.NewSessionConnected += MyServer_NewSessionConnected; this.SessionClosed += MyServer_SessionClosed; } bool Setup(IRootConfig rootConfig,IServerConfig config) { .Setup(rootConfig,config); } OnStarted() { .OnStarted(); } OnStopped() { .OnStopped(); } MyServer_NewSessionConnected(MySession session) { LogHelper.Log("新客户端连接,SessionID=" + session.SessionID.Substring(session.SessionID.Length - 6).toupper()); } MyServer_SessionClosed(MySession session,CloseReason value) { LogHelper.Log(客户端失去连接,SessionID=6).toupper() + ,原因:" + value); } } }
六、实现CommandBase<MySession,MyRequestInfo>:
SuperSocket.socketBase.Command; class EC : CommandBase<MySession,1)"> ExecuteCommand(MySession session,MyRequestInfo requestInfo) { LogHelper.Log(客户端 发来消息: requestInfo.Body); byte[] bytes = ASCIIEncoding.UTF8.GetBytes(消息收到"); session.Send(bytes,,bytes.Length); } } }
七、服务端Form1.cs代码:
System.ComponentModel; System.Data; System.Drawing; System.Windows.Forms; partial Form1 : Form { private MyServer _myServer; Form1() { InitializeComponent(); LogHelper.Init(thisprivate void Form1_Load(object sender,EventArgs e) { _myServer = MyServer(); ServerConfig serverConfig = ServerConfig() { Port = 2021 }; _myServer.Setup(serverConfig); _myServer.Start(); } void button1_Click(foreach (MySession session in _myServer.GetAllSessions()) { 服务端广播消息); session.Send(bytes,bytes.Length); } } } }
八、客户端Form1.cs代码:
System.IO; System.Net; System.Net.sockets; System.Windows.Forms; SuperSocketClient { Socket _socket; NetworkStream _socketStream; Form1() { InitializeComponent(); } new IPEndPoint(IPAddress.Parse(127.0.0.1"),1)">); _socket = Socket(serverAddress.AddressFamily,SocketType.Stream,ProtocolType.Tcp); _socket.Connect(serverAddress); _socketStream = NetworkStream(_socket); //socketasynceventargs socketAsyncArgs = new socketasynceventargs(); byte[] buffer = new byte[10240]; socketAsyncArgs.SetBuffer(buffer,buffer.Length); socketAsyncArgs.Completed += ReciveAsync; _socket.ReceiveAsync(socketAsyncArgs); Receive(_socket); } { Random rnd = Random(); string cmd = EC; string msg = 测试消息00" + rnd.Next(0,1)">100).ToString(00); Send(cmd,msg); }); } void Send(string cmd,1)"> msg) { byte[] cmdBytes = Encoding.ASCII.GetBytes(cmd); byte[] msgBytes = Encoding.UTF8.GetBytes(msg); byte[] lengthBytes = BitConverter.GetBytes((short)msgBytes.Length); _socketStream.Write(cmdBytes,cmdBytes.Length); _socketStream.Write(lengthBytes,lengthBytes.Length); _socketStream.Write(msgBytes,msgBytes.Length); _socketStream.Flush(); Log(发送: msg); } void ReciveAsync( obj,socketasynceventargs e) { if (e.BytesTransferred > ) { string data = ASCIIEncoding.UTF8.GetString(e.Buffer,e.BytesTransferred); Log(接收: data); } } Receive(Socket socket) { Task.Factory.StartNew(() =>try { while (true) { byte[] buffer = byte[10240]; int receiveCount = _socket.Receive(buffer,buffer.Length,SocketFlags.None); if (receiveCount > ) { string data = ASCIIEncoding.UTF8.GetString(buffer,receiveCount); Log( data); } } } catch (Exception ex) { Log(Receive出错:" + ex.Message + \r\n ex.StackTrace); } },TaskCreationoptions.LongRunning); } #region Log /// <summary> /// 输出日志 </summary> void Log( log) { if (!.Isdisposed) { this.BeginInvoke(new Action(() => { txtLog.AppendText(DateTime.Now.ToString(HH:mm:ss.fff") + " " + log + \r\n\r\n); })); } } #endregion } }
辅助工具类LogHelper:
SuperSocketServer; Utils { LogHelper { static Form1 _frm; TextBox _txtLog; static Init(Form1 frm,TextBox txt) { _frm = frm; _txtLog = txt; } _frm.Isdisposed) { _frm.BeginInvoke( { _txtLog.AppendText(DateTime.Now.ToString(); })); } } } }
测试截图:
问题:
1、客户端使用socketasynceventargs异步接收数据,第一次能收到数据,后面就收不到了,不知道什么原因,同步接收数据没问题
2、SuperSocket源码中的示例和网上相关的博客,客户端要么是原生Socket实现,要么是Socket调试工具,客户端不需要复杂一点的功能或数据结构吗?客户端不需要解包吗?SuperSocket不能用来写客户端吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。