private void ProcessData(Conn conn) { //小于长度字节 if (conn.buffCount < sizeof(Int32)) { return; } //消息长度 Array.Copy(conn.readBuff, conn.lenBytes, sizeof(Int32)); conn.msgLength = BitConverter.ToInt32(conn.lenBytes, 0); if (conn.buffCount < conn.msgLength + sizeof(Int32)) { return; } //处理消息 Protocol.ProtocolBase protocol = proto.Decode(conn.readBuff, sizeof(Int32), conn.msgLength); HandleMsg(conn, protocol); //清除已处理的消息 int count = conn.buffCount - conn.msgLength - sizeof(Int32); Array.Copy(conn.readBuff, sizeof(Int32) + conn.msgLength, conn.readBuff, 0, count); conn.buffCount = count; if (conn.buffCount > 0) { ProcessData(conn); } }
//开启服务器 public void Start(string host, int port) { timer.Elapsed += new System.Timers.ElapsedEventHandler(HandleMainTimer); timer.AutoReset = false; timer.Enabled = true; proto = new Protocol.ProtocolBytes(); //链接池 conns = new Conn[MAX_CONN]; for (int i = 0; i < MAX_CONN; i++) { conns[i] = new Conn(); } //Socket listenfd = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //Bind IPAddress ipAdr = IPAddress.Parse(host); IPEndPoint ipEp = new IPEndPoint(ipAdr, port); listenfd.Bind(ipEp); //Listen listenfd.Listen(MAX_CONN); //Accept listenfd.BeginAccept(AcceptCb, null); Console.WriteLine("[服务器]启动成功 listening in:" + host + ":" + port); }
public static void Process(Conn conn, Protocol.ProtocolBase protoBase) { string name = protoBase.GetName(); var player = MemoryData.players[conn]; switch (name) { case "FindMatch": BattleMsgHandler.FindMatch(player, protoBase); break; case "CancelFindMatch": BattleMsgHandler.CancelFindMatch(player, protoBase); break; case "Progress": BattleMsgHandler.UpdateGameLoadProgress(player, protoBase); break; case "FrameData": BattleMsgHandler.UpdateInput(player, protoBase); break; case "EndGame": BattleMsgHandler.EndGame(player, protoBase); break; case "HeartBeat": ConnMsgHandler.HeartBeat(conn, protoBase); break; } }
//广播 public void Broadcast(Protocol.ProtocolBase protocol) { for (int i = 0; i < conns.Length; i++) { if (!conns[i].isUse) { continue; } Send(conns[i], protocol); } }
//广播 private void Broadcast(Protocol.ProtocolBase protocol) { foreach (var p in m_players) { lock (p.conn) { if (p.conn != null && p.conn.isUse) { p.conn.Send(protocol); } } } }
//发送 public void Send(Protocol.ProtocolBase protocol) { byte[] bytes = protocol.Encode(); byte[] length = BitConverter.GetBytes(bytes.Length); byte[] sendbuff = length.Concat(bytes).ToArray(); try { this.socket.BeginSend(sendbuff, 0, sendbuff.Length, SocketFlags.None, null, null); } catch (Exception e) { Console.WriteLine("[发送消息]" + this.GetAdress() + " : " + e.Message); } }
private void HandleMsg(Conn conn, Protocol.ProtocolBase protoBase) { Handler.Process(conn, protoBase); }
public static void HeartBeat(Conn conn, Protocol.ProtocolBase proto) { conn.lastTickTime = TimeUtility.GetTimeStamp(); //Console.WriteLine("[HeartBeat]" + conn.GetAdress()); }