コード例 #1
0
        public void OnDataReceived(byte[] buffer, long offset, long size)
        {
            lock (messageLocker)
            {
                messageBuffer.WriteBytes(buffer, (int)offset, (int)size);

                if (messageBuffer.Length > 0)
                {
                    byte[][] dataBytesArr = messageBuffer.ReadMessages();
                    if (dataBytesArr != null && dataBytesArr.Length > 0)
                    {
                        foreach (var dataBytes in dataBytesArr)
                        {
                            if (messageDecoder.DecodeMessage(dataBytes, out int msgID, out byte[] msgBytes))
                            {
                                ClientMessageData data = messageDataPool.Get();
                                data.MsgId    = msgID;
                                data.MsgBytes = msgBytes;
                                messageDatas.Add(data);
                            }
                            else
                            {
                                NetLogger.Error(LOG_TAG, "error");
                            }
                        }
                    }
                }
コード例 #2
0
 public void RegisterMessageHandler(int msgID, ServerMessageHandler handler)
 {
     if (!messageHandlerDic.ContainsKey(msgID))
     {
         messageHandlerDic.Add(msgID, handler);
     }
     else
     {
         NetLogger.Error(LOG_TAG, $"The handler({msgID}) has been registed");
     }
 }
コード例 #3
0
 public bool StartServer(string name, int port, Func <IMessageEncoder> encoderCreator = null, Func <IMessageDecoder> decoderCreator = null)
 {
     if (!networkDic.ContainsKey(name))
     {
         ServerNetwork network = new ServerNetwork(name, IPAddress.Parse("127.0.0.1"), port);
         network.MessageEncoderCreateFunc = encoderCreator ?? (() => new DefaultMessageEncoder());
         network.MessageDecoderCreateFunc = decoderCreator ?? (() => new DefaultMessageDecoder());
         if (network.Start())
         {
             networkDic.Add(name, network);
             return(true);
         }
         else
         {
             NetLogger.Error(LOG_TAG, $"The server which named({name}) is not started");
             return(false);
         }
     }
     return(true);
 }
コード例 #4
0
        protected override void OnReceived(byte[] buffer, long offset, long size)
        {
            if (MessageDecoder == null)
            {
                NetLogger.Error(LOG_TAG, "The decoder is not null");
                return;
            }
            messageBuffer.WriteBytes(buffer, (int)offset, (int)size);

            byte[][] dataBytesArr = messageBuffer.ReadMessages();
            if (dataBytesArr != null)
            {
                foreach (var dataBytes in dataBytesArr)
                {
                    if (MessageDecoder.DecodeMessage(dataBytes, out int msgId, out byte[] msgBytes))
                    {
                        SessionHandler.OnMessageReceived(Id, msgId, msgBytes);
                    }
                }
            }
        }
コード例 #5
0
        /// <summary>
        /// Tries to open a UdpSocket, starting with port, and if port is already
        /// in use, incrementing and retrying until it hits maxPort.
        /// </summary>
        /// <param name="port"></param>
        /// <param name="maxPort"></param>
        /// <param name="maxQueueSize"></param>
        /// <param name="netLogger"></param>
        public UdpSocket(int port, int maxPort, int maxQueueSize, NetLogger netLogger)
        {
            // check if port is available
            IPEndPoint[] actives = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners();
            while (true)
            {
                bool found = false;
                for (int i = 0; i < actives.Length; i++)
                {
                    if (actives[i].Port == port)
                    {
                        port++;
                        found = true;
                        break;
                    }
                }

                if (port > maxPort)
                {
                    throw new Exception("Tried to open UDP socket, but first available port '" + port + "' exceeded maximum port '" + maxPort + "'");
                }

                if (!found)
                {
                    break;
                }
            }

            Port = port;

            NetLogger = netLogger;
            UdpClient = new UdpClient(port);

            DirectFromPoint = new IPEndPoint(IPAddress.Loopback, port);

            // important note:
            // the pool here is ordered, which means returning an item is less efficient
            // but it guarantees that the last receipt, which is the empty one being
            // written to, stays at the end of the pool.
            Pool = new ReArrayIdPool <Receipt>(10, maxQueueSize,
                                               PoolCreate, (obj) => { obj.Clear(); });
            WritingReceipt = Pool.Request();

            CancellationTokenSource = new CancellationTokenSource();
            CancellationToken ctoken = CancellationTokenSource.Token;

            Task.Run(async() =>
            {
                if (NetLogger.On)
                {
                    NetLogger.Log("Opening [UDPv6] listener on port " + port + "...");
                }

                while (!ctoken.IsCancellationRequested)
                {
                    try
                    {
                        Receipt rec = await ReceiveAsync();
                        // the receipt, by nature of its existence, goes into the queue.
                    }
                    catch (Exception e)
                    {
                        if (NetLogger.On)
                        {
                            NetLogger.Error("UdpClient listener encountered exception on " + port, e);
                        }
                    }
                }

                if (NetLogger.On)
                {
                    NetLogger.Log("Closing listener on port " + port + "...");
                }

                try
                {
                    UdpClient.Close();
                    UdpClient.Dispose();
                }
                catch
                {
                }
            });
        }