supersocket这款组件,让不懂tcp/ip的人都能开发出网络应用。我们不必在开发与自己主要应用不相关的代码了,主要精力都能放在设计业务逻辑上面了。 现在使用现成又完备的组件,真是
public class DataRequestInfo : IRequestInfo { public string Key { get; set; } public byte[] Data { get; set; } public byte[] DataSend { get; set; } public DataRequestInfo(string key,byte[] header, byte[] bodyBuffer) { Key= key; int length = ByteConvertHelper.byteArrayToInt(header); Data = new byte[length]; Array.Copy(bodyBuffer, 0, Data, 0, length); DataSend=new byte[length+4]; Array.Copy(header, 0, DataSend, 0, header.Length); Array.Copy(bodyBuffer, 0, DataSend, header.Length, bodyBuffer.Length); } }View Code Appsession:是连接服务器的一个会话,支持继承。当客户端连接上服务端后,服务端就会产生一个Appsession
public class PaintAppsession : AppSession<PaintAppsession, DataRequestInfo> { public string IDKey { get { return base.SessionID; } } // public string NickName { get; set; } public ClientPlayerInfo ClientPlayerInfo { get; set; } public bool isReady { get; set; } protected override void HandleException(Exception e) { // var a = e; } }View Code AppServer就表示服务端了,也支持继承,AppServer这种是抽象类,必须自己继承。
public class PaintAppServer : AppServer<PaintAppsession, DataRequestInfo> { public PaintAppServer(IReceiveFilterFactory<DataRequestInfo> protocol) : base(protocol) { } }View Code FixedHeaderReceiveFilter表示接收头部固定长度的字节,头部header长度定义为4,每次发送的字节前4个的自己是可以自己定义的,比如存发送的数据包的大小。这个类的作用是把从网络中收到的字节组装成DataRequestInfo。
internal class MyServerReceiveFilter : FixedHeaderReceiveFilter<DataRequestInfo> { public MyServerReceiveFilter(): base(4) { } protected override int GetBodyLengthFromHeader(byte[] header, int offset, int length) { var data=new byte[length]; Array.Copy(header, offset, data, 0, length); var len = ByteConvertHelper.byteArrayToInt(data); return len; } protected override DataRequestInfo ResolveRequestInfo(ArraySegment<byte> header, byte[] bodyBuffer, int offset, int length) { var data = new byte[length]; Array.Copy(bodyBuffer.ToArray(), offset, data, 0, length); return new DataRequestInfo("key1",header.ToArray(), data); } public override DataRequestInfo Filter(byte[] readBuffer, int offset, int length, bool toBeCopied, out int rest) { return base.Filter(readBuffer, offset, length, toBeCopied, out rest); } }View Code
使用:
appServer = new PaintAppServer(new DefaultReceiveFilterFactory<MyServerReceiveFilter, DataRequestInfo>()); 配置监听:IServerConfig m_Config = new ServerConfig { Port = port, Ip = "Any", MaxConnectionNumber = 1000, Mode = SocketMode.Tcp, Name = "CustomProtocolServer", MaxRequestLength = 10240 }; if (appServer.Setup(m_Config, logFactory: new ConsoleLogFactory())){;}View Code 打开: appServer.Start();