예제 #1
0
 public void Setup()
 {
     msg = null;
     service = new NetMessageService(8668);
     service.Start();
     service.MessageReceived += HandleServiceMessageReceived;
 }
예제 #2
0
        protected override void OnTcpMessage(SocketToken token, INetMessage message)
        {
            if (message is PanRequest)
            {
                PanRequest req = message as PanRequest;
                bool       bo  = APP.gameMap.WriteColumn(req.colomn.posX, req.colomn.posY, req.colomn.color, req.size);

                Log.L(string.Format("User {0}/{1}   Pan   [{2},{3}]    {4}  {5}", req.account, req.name, req.colomn.posX, req.colomn.posY, req.colomn.color, req.size));
                net.SendTcpMessageToAll(new PanBroadCast()
                {
                    colomn  = req.colomn,
                    account = req.account,
                    name    = req.name
                    , size  = req.size
                });
            }
            if (message is AskPanRequest)
            {
                AskPanRequest req = message as AskPanRequest;

                APP.gameMap.BroadCastMap((resp) =>
                {
                    APP.net.SendTcpMessage(token, resp);
                });

                Log.L(string.Format("User {0}/{1}   aaskForMap  ", req.account, req.name));
            }
        }
        public bool HandleMessage(INetMessage message)
        {
            int unitId = message.Reader.GetInt();

            var          serializePositionData = message.Reader.GetString();
            PositionData positionData          =
                MessageSerializerService.DeserializeObjectOfType <PositionData>(serializePositionData);

            var session = SessionCache.Instance.GetSessionById(message.Client.CurrentSessionId);

            if (session == null || !session.IsStarted)
            {
                return(true);
            }

            if (session.Units.ContainsKey(unitId))
            {
                NetDataWriter _dataWriter = new NetDataWriter();
                _dataWriter.Reset();
                _dataWriter.Put((byte)NetOperationCode.SendUnit);
                _dataWriter.Put(unitId);
                _dataWriter.Put(serializePositionData);

                foreach (var p in session.Players)
                {
                    session.SendToAll(_dataWriter, DeliveryMethod.Sequenced);
                }
            }

            return(true);
        }
예제 #4
0
        public bool HandleMessage(INetMessage message)
        {
            Console.WriteLine($"JoinSessionHandler. PeerId: {message.Client.NetPeer.Id}");

            byte[] sessionId = new byte[12];
            message.Reader.GetBytes(sessionId, 12);

            NetDataWriter writer = new NetDataWriter();

            writer.Put((byte)NetOperationCode.JoinSession);

            if (message.Client.CurrentSessionId != null || !SessionCache.Instance.JoinSession(sessionId, message.Client))
            {
                writer.Put((byte)NetErrorCode.SessionConnectedFailed);
            }
            else
            {
                writer.Put((byte)NetErrorCode.Success);

                writer.Put(message.Client.Units.Count);
                foreach (var u in message.Client.Units)
                {
                    writer.Put(MessageSerializerService.SerializeObjectOfType(u.Value.UnitData));
                }
            }

            message.Client.NetPeer.Send(writer, DeliveryMethod.ReliableOrdered);
            return(true);
        }
 protected override void OnTcpMessage(SocketToken token, INetMessage message)
 {
     if (message is RegisterResponse)
     {
         APP.message.Publish(this, 0, null, message);
     }
 }
예제 #6
0
        public void BroadcastMessage(INetMessage msg, IRecipientFilter filter)
        {
            if (filter.IsInitMessage())
            {
                if (!msg.WriteToBuffer(Signon))
                {
                    Out.Warning("BaseServer.BroadcastMessage: Init message would overflow signon buffer!");
                }

                return;
            }

            msg.SetReliable(filter.IsReliable());

            foreach (var client in Clients)
            {
                if (!client.IsSpawned())
                {
                    continue;
                }

                if (!client.NetChannel.SendNetMsg(msg))
                {
                    if (msg.IsReliable())
                    {
                        Out.Warning("BaseServer.BroadcastMessage: Reliable filter message overflow for client {0}", client.GetClientName());
                    }
                }
            }
        }
예제 #7
0
        private void OnTcpRec(SocketToken token, BufferSegment seg)
        {
            tcpTokenPool.RefreshConnectionToken(token);
            PacketReader pr;

            if (!_tcpPkgs.TryGetValue(token, out pr))
            {
                pr = new PacketReader(Configs.net.TCPBuffersize * 4096);
                _tcpPkgs.Add(token, pr);
            }

            pr.Set(seg.buffer, seg.offset, seg.count);


            var pkgs = pr.Get();

            if (pkgs != null)
            {
                for (int i = 0; i < pkgs.Count; i++)
                {
                    var         p      = pkgs[i];
                    Type        type   = NetMessageTool.GetTypeByID(p.pkgID);
                    string      msgstr = encoding.GetString(p.message);
                    INetMessage msg    = Json.ToObject(type, msgstr) as INetMessage;
                    APP.env.modules.Loom.RunOnMainThread(() =>
                    {
                        if (onTcpMessage != null)
                        {
                            onTcpMessage(token, msg);
                        }
                    });
                }
            }
        }
예제 #8
0
        protected override void OnTcpMessage(SocketToken token, INetMessage message)
        {
            if (message is LoginRequest)
            {
                LoginRequest req = message as LoginRequest;
                string       err;
                string       name;
                bool         bo = APP.datas.users.TryLogin(req.account, req.psd, out name, out err);
                Log.L(string.Format("User Login  {0}  {1}  {2}  {3}", req.account, name, req.psd, err));

                net.SendTcpMessage(token, new LoginResponse()
                {
                    account = req.account,
                    psd     = req.psd,
                    name    = name,
                    sucess  = bo,
                    err     = err
                });
                if (bo)
                {
                    net.SendTcpMessageToAll(new loginBroadCast()
                    {
                        account = req.account,
                        name    = name
                    });
                }
            }
        }
        public bool HandleMessage(INetMessage message)
        {
            Console.WriteLine($"SetUnitPositionHandler. PeerId: {message.Client.NetPeer.Id}");

            if (message.Client.CurrentSessionId == null)
            {
                return(true);
            }

            var session = SessionCache.Instance.GetSessionById(message.Client.CurrentSessionId);

            if (session == null || session.IsStarted)
            {
                return(true);
            }

            int          unitId       = message.Reader.GetInt();
            PositionData positionData = MessageSerializerService.DeserializeObjectOfType <PositionData>(message.Reader.GetString());

            if (session.Units.ContainsKey(unitId))
            {
                session.Units[unitId].UnitData.PositionData = positionData;
            }

            return(true);
        }
예제 #10
0
        public bool HandleMessage(INetMessage message)
        {
            if (message.Client.CurrentSessionId == null)
            {
                return(true);
            }

            var session = SessionCache.Instance.GetSessionById(message.Client.CurrentSessionId);

            if (session == null)
            {
                return(true);
            }

            var senderId = message.Reader.GetInt();
            var targetId = message.Reader.GetInt();

            if (!session.Units.ContainsKey(targetId) || !session.Units.ContainsKey(senderId))
            {
                return(true);
            }

            NetDataWriter _dataWriter = new NetDataWriter();

            _dataWriter.Reset();
            _dataWriter.Put((byte)NetOperationCode.SendAttackUnit);
            _dataWriter.Put(senderId);
            _dataWriter.Put(targetId);

            session.SendToAll(_dataWriter, DeliveryMethod.Sequenced);

            return(true);
        }
예제 #11
0
 protected override void OnTcpMessage(SocketToken token, INetMessage message)
 {
     if (message is ChatBroadCast)
     {
         APP.message.Publish(this, 0, null, message);
     }
 }
예제 #12
0
        private BufferSegment NetMessageToBufferSegment(INetMessage message)
        {
            var    bytes = encoding.GetBytes(Json.ToJsonString(message));
            Packet pac   = new Packet(1, NetMessageTool.GetIDByType(message.GetType()), 1, bytes);

            bytes = pac.Pack();
            return(new BufferSegment(bytes, 0, bytes.Length));
        }
예제 #13
0
        public void SendTcpMessageToAll(INetMessage message)
        {
            var ie = tcpTokenPool.ReadNext().GetEnumerator();

            while (ie.MoveNext())
            {
                SendTcpMessage(ie.Current.Token, message);
            }
        }
예제 #14
0
 protected override void OnTcpMessage(SocketToken token, INetMessage message)
 {
     if (message is ChatBroadCast)
     {
         ChatBroadCast c = message as ChatBroadCast;
         net.SendTcpMessageToAll(message);
         Log.L(string.Format("Chat {0}/{1}   {2}  ", c.acc, c.name, c.message));
     }
 }
 protected override void OnTcpMessage(SocketToken token, INetMessage message)
 {
     if (message is LoginResponse)
     {
         APP.message.Publish(this, 0, null, message);
     }
     if (message is loginBroadCast)
     {
         APP.message.Publish(this, 0, null, message);
     }
 }
예제 #16
0
        public static void Send(this INetMessage message, NetworkDestination destination, Int32 recievedFrom = -1)
        {
            if (destination.ShouldRun())
            {
                message.OnRecieved();
            }

            if (destination.ShouldSend())
            {
                Header header = destination.GetHeader(NetworkCore.GetNetworkCoreHash(message.GetType()));

                if (NetworkServer.active)
                {
                    for (Int32 i = 0; i < NetworkServer.connections.Count; ++i)
                    {
                        if (i == recievedFrom)
                        {
                            continue;
                        }

                        NetworkConnection conn = NetworkServer.connections[i];
                        if (conn == null)
                        {
                            continue;
                        }

                        if (NetworkServer.localClientActive && NetworkServer.localConnections.Contains(conn))
                        {
                            continue;
                        }

                        using (Writer netWriter = NetworkCore.GetWriter(NetworkCore.messageIndex, conn, NetworkCore.qos))
                        {
                            NetworkWriter writer = netWriter;
                            writer.Write(header);
                            writer.Write(message);
                        }
                    }
                }
                else if (NetworkClient.active)
                {
                    using (Writer netWriter = NetworkCore.GetWriter(NetworkCore.messageIndex, ClientScene.readyConnection, NetworkCore.qos))
                    {
                        NetworkWriter writer = netWriter;
                        writer.Write(header);
                        writer.Write(message);
                    }
                }
            }
        }
예제 #17
0
        public static int Dispatch(ByteReader reader, ReceiveMsgCallback callback)
        {
            if (callback == null)
            {
                return(0);
            }

            /*
             * 协议格式:
             *      short: 协议大小
             *      short: 协议号
             *      动态长度
             */
            int LastPos = 0;

            try
            {
                do
                {
                    int msg_len   = reader.ReadShort();
                    int msg_start = reader.GetPos();

                    int         id  = reader.ReadShort();
                    INetMessage msg = NetCenter.Recognize(id, reader);
                    if (msg == null)
                    {
                        break;
                    }

                    // 协议大小不对!
                    if (msg_len != (reader.GetPos() - msg_start))
                    {
                        break;
                    }

                    LastPos = reader.GetPos();

                    try
                    {
                        callback(id, msg);
                    }
                    catch (Exception)
                    { }
                }while (!reader.IsEnd());
            }
            catch (Exception)
            { }

            return(LastPos);
        }
예제 #18
0
        public static INetMessage Recognize(int id, ByteReader reader)
        {
            if (!Dict.ContainsKey(id))
            {
                return(null);
            }

            Type        t   = Dict[id];
            INetMessage msg = (INetMessage)System.Activator.CreateInstance(t, null);

            msg.Decode(reader);

            return(msg);
        }
예제 #19
0
        /// <summary>
        /// Writes given network message into a given stream.
        /// </summary>
        /// <param name="message">The message to write.</param>
        /// <param name="stream">The stream to write message to.</param>
        /// <returns>true if message was written successfully, false otherwise</returns>
        private bool WriteMessage(INetMessage message, MemoryStream stream)
        {
            BinaryWriter writer = new BinaryWriter(stream);

            writer.Write(PROTOCOL_ID);
            writer.Write((byte)message.MessageId);
            if (!message.Write(writer))
            {
                Client.FatalError("Failed to write network message " + message.MessageId);
                return(false);
            }

            statistics.RecordSendMessage(message.MessageId, stream.Length);
            return(true);
        }
예제 #20
0
        public static byte[] Encoder(INetMessage message)
        {
            var ty = message.GetType();
            var id = keys[ty];

            using (var memory = new MemoryStream())
            {
                Serializer.Serialize(memory, message);
                var data = new byte[memory.Length + 4];
                Array.Copy(BitConverter.GetBytes((ushort)data.Length), 0, data, 0, 2);
                Array.Copy(BitConverter.GetBytes((ushort)id), 0, data, 2, 2);
                Array.Copy(memory.ToArray(), 0, data, 4, memory.Length);
                return(data);
            }
        }
예제 #21
0
        public bool SendNetMsg(INetMessage msg, bool forceReliable = false)
        {
            if (_remoteAddress == null)
            {
                return(true);
            }

            var stream = StreamUnreliable;

            if (msg.IsReliable() || forceReliable)
            {
                stream = StreamReliable;
            }

            return(msg.WriteToBuffer(stream));
        }
예제 #22
0
        private void OnTCPRec(SocketToken token, BufferSegment seg)
        {
            tcpPkgReader.Set(seg.buffer, seg.offset, seg.count);
            var pkgs = tcpPkgReader.Get();

            if (pkgs != null)
            {
                pkgs.ForEach((p) =>
                {
                    INetMessage msg = Json.ToObject(NetMessageTool.GetTypeByID(p.pkgID), encoding.GetString(p.message)) as INetMessage;
                    Framework.env1.modules.Loom.RunOnMainThread(() =>
                    {
                        onTcpMessage?.Invoke(token, msg);
                    });
                });
            }
        }
예제 #23
0
 public MessageRaw(INetMessage netMsg)
 {
     using (var memoryStream = new MemoryStream())
     {
         using (var writer = new BinaryWriter(memoryStream))
         {
             netMsg.OnSerialize(writer);
             var idField = netMsg.GetType().GetField("ID", BindingFlags.Static | BindingFlags.Public);
             if (idField == null)
             {
                 throw new Exception();
             }
             type   = (byte)(int)idField.GetValue(null);
             length = (short)(memoryStream.Length + 3);
             data   = memoryStream.GetBuffer();
         }
     }
 }
예제 #24
0
 protected override void OnTcpMessage(SocketToken token, INetMessage message)
 {
     if (message is RegisterRequest)
     {
         RegisterRequest req = message as RegisterRequest;
         string          err;
         bool            bo = APP.datas.users.AddUser(req.account, req.name, req.psd, out err);
         Log.L(string.Format("User Register  {0}  {1}  {2}  {3}", req.account, req.name, req.psd, err));
         net.SendTcpMessage(token, new RegisterResponse()
         {
             account = req.account,
             psd     = req.psd,
             name    = req.name,
             sucess  = bo,
             err     = err
         });
     }
 }
예제 #25
0
        public void BroadcastMessage(INetMessage msg, bool onlyActive = false, bool reliable = false)
        {
            foreach (var client in Clients)
            {
                if ((onlyActive && !client.IsActive()) || !client.IsSpawned())
                {
                    continue;
                }

                if (!client.NetChannel.SendNetMsg(msg, reliable))
                {
                    if (msg.IsReliable() || reliable)
                    {
                        Out.Warning("BaseServer.BroadcastMessage: Reliable broadcast message overflow for client {0}", client.GetClientName());
                    }
                }
            }
        }
예제 #26
0
        public static void Send(Socket owner, INetMessage msg)
        {
            ByteWriter writer = new ByteWriter();

            writer.Write(msg.GetID());
            msg.Encode(writer);

            short      cnt     = (short)writer.GetBytes().Length;
            ByteWriter writer2 = new ByteWriter();

            writer2.Write(cnt);

            List <byte> ret = new List <byte>();

            ret.AddRange(writer2.GetBytes());
            ret.AddRange(writer.GetBytes());

            owner.Send(ret.ToArray());
        }
예제 #27
0
        public bool HandleMessage(INetMessage message)
        {
            if (message.Client.CurrentSessionId == null)
            {
                return(true);
            }

            var session = SessionCache.Instance.GetSessionById(message.Client.CurrentSessionId);

            if (session == null)
            {
                return(true);
            }

            var senderId = message.Reader.GetInt();
            var targetId = message.Reader.GetInt();

            if (!session.Units.ContainsKey(senderId) || !session.Units.ContainsKey(targetId))
            {
                return(true);
            }

            lock (session.Units)
            {
                var sender = session.Units[senderId];
                var target = session.Units[targetId];

                target.GetDamage(sender);

                NetDataWriter _dataWriter = new NetDataWriter();
                _dataWriter.Reset();
                _dataWriter.Put((byte)NetOperationCode.SendDamage);
                _dataWriter.Put(senderId);
                _dataWriter.Put(targetId);
                _dataWriter.Put(target.UnitData.Health);

                Console.WriteLine($"{senderId} / {targetId} / {target.UnitData.Health}");

                session.SendToAll(_dataWriter, DeliveryMethod.Sequenced);
                return(true);
            }
        }
예제 #28
0
        public static void Send(this INetMessage message, NetworkDestination destination)
        {
            if (destination.ShouldRun())
            {
                message.OnReceived();
            }

            if (destination.ShouldSend())
            {
                var header = destination.GetHeader(NetworkingAPI.GetNetworkHash(message.GetType()));

                if (NetworkServer.active)
                {
                    for (int i = 0; i < NetworkServer.connections.Count; ++i)
                    {
                        NetworkConnection conn = NetworkServer.connections[i];
                        if (conn == null)
                        {
                            continue;
                        }
                        if (NetworkServer.localClientActive && NetworkServer.localConnections.Contains(conn))
                        {
                            continue;
                        }

                        using (Writer netWriter = NetworkingAPI.GetWriter(NetworkingAPI.MessageIndex, conn, QosType.Reliable)) {
                            NetworkWriter writer = netWriter;
                            writer.Write(header);
                            writer.Write(message);
                        }
                    }
                }
                else if (NetworkClient.active)
                {
                    using (Writer netWriter = NetworkingAPI.GetWriter(NetworkingAPI.MessageIndex, ClientScene.readyConnection, QosType.Reliable)) {
                        NetworkWriter writer = netWriter;
                        writer.Write(header);
                        writer.Write(message);
                    }
                }
            }
        }
예제 #29
0
        public static List <INetMessage> Decode(BitStream stream)
        {
            List <INetMessage> messages = new List <INetMessage>();

            while (stream.Cursor < (stream.Length - SourceConstants.NETMSG_TYPE_BITS))
            {
                NetMessageType type = (NetMessageType)stream.ReadByte(SourceConstants.NETMSG_TYPE_BITS);

                if (type == NetMessageType.NET_NOOP)
                {
                    continue;
                }

                INetMessage newMsg = CreateNetMessage(type);
                newMsg.ReadMsg(stream);
                messages.Add(newMsg);
            }

            return(messages);
        }
예제 #30
0
        public bool HandleMessage(INetMessage message)
        {
            int unitId = message.Reader.GetInt();

            var          serializePositionData = message.Reader.GetString();
            PositionData positionData          =
                MessageSerializerService.DeserializeObjectOfType <PositionData>(serializePositionData);

            var session = SessionCache.Instance.GetSessionById(message.Client.CurrentSessionId);

            if (session == null || !session.IsStarted)
            {
                return(true);
            }

            if (session.Units.ContainsKey(unitId))
            {
                session.Units[unitId].UnitData.PositionData = positionData;
            }

            return(true);
        }
예제 #31
0
 void AddMessage(INetMessage message)
 {
     m_pendingMessages.Enqueue(message);
     Report("Sending Message: ID(" + message.MessageID + ")");
 }
예제 #32
0
 public void SendMessage(INetMessage message)
 {
     if(this.Connected)
       {
     if(clientChannel != null)
       clientChannel.SendMessage(Serializer.SerializeObject(message));
     else
       callbackChannel.MessageReceived(Serializer.SerializeObject(message));
       }
 }
예제 #33
0
        /// <summary>
        /// 接收一条完整的 <seealso cref="INetMessage"/> 数据内容 ->
        /// Receive a complete <seealso cref="INetMessage"/> data content
        /// </summary>
        /// <param name="socket">网络的套接字</param>
        /// <param name="timeOut">超时时间</param>
        /// <param name="netMessage">消息的格式定义</param>
        /// <returns>带有是否成功的byte数组对象</returns>
        protected OperateResult <byte[]> ReceiveByMessage(Socket socket, int timeOut, INetMessage netMessage)
        {
            HslTimeOut hslTimeOut = new HslTimeOut( )
            {
                DelayTime  = timeOut,
                WorkSocket = socket,
            };

            if (timeOut > 0)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadPoolCheckTimeOut), hslTimeOut);
            }

            // 接收指令头
            OperateResult <byte[]> headResult = Receive(socket, netMessage.ProtocolHeadBytesLength);

            if (!headResult.IsSuccess)
            {
                hslTimeOut.IsSuccessful = true;
                return(headResult);
            }

            netMessage.HeadBytes = headResult.Content;
            int contentLength = netMessage.GetContentLengthByHeadBytes( );

            if (contentLength <= 0)
            {
                hslTimeOut.IsSuccessful = true;
                return(headResult);
            }

            OperateResult <byte[]> contentResult = Receive(socket, contentLength);

            if (!contentResult.IsSuccess)
            {
                hslTimeOut.IsSuccessful = true;
                return(contentResult);
            }

            // 防止没有实例化造成后续的操作失败
            hslTimeOut.IsSuccessful = true;
            netMessage.ContentBytes = contentResult.Content;
            return(OperateResult.CreateSuccessResult(SoftBasic.SpliceTwoByteArray(headResult.Content, contentResult.Content)));
        }
예제 #34
0
 void HandleServiceMessageReceived(object arg1, INetMessageServiceCallback arg2, Byte[] message)
 {
     msg = (INetMessage)Communication.Serializer.DeserializeObject(message);
 }