예제 #1
0
        public void Start()
        {
            mTcpListener.Start();
            Task.Factory.StartNew(async() =>
            {
                while (true)
                {
                    var tcpClient  = mTcpListener.AcceptTcpClient();
                    var connection = new Connection(tcpClient, mRouter, mDictionary);
                    var sessionID  = rnd.Next();
                    mConnections.Add(sessionID, connection);

                    var session = new SetupSession()
                    {
                        SessionId = sessionID, Address = mUdpEndPoint.Address.ToString(), port = mUdpEndPoint.Port
                    };
                    await connection.SendReliable(session);
                    connection.SetupUnreliable(sessionID, new IPEndPoint(IPAddress.Parse(session.Address), session.port));
                }
            });

            Task.Factory.StartNew(async() =>
            {
                while (true)
                {
                    var received = await mUdpListener.ReceiveAsync();
                    using (var stream = new MemoryStream(received.Buffer))
                    {
                        var header = new UdpMessageHeader(stream);
                        if (mConnections.ContainsKey(header.SessionId))
                        {
                            var connection = mConnections[header.SessionId];
                            var response   = connection.HandleMessage(header.TypeID, header.MessageID, stream);

                            if (response != null)
                            {
                                await connection.SendUnreliable(response, header.MessageID);
                            }
                        }
                    }
                }
            });
        }
예제 #2
0
        public async Task SendUnreliable(Message msg, int msgId = 0)
        {
            while (mUdpClient == null)
            {
                ;
            }

            var header = new UdpMessageHeader()
            {
                TypeID = mMsgDict.GetTypeID(msg.GetType()), SessionId = mSessionId, MessageID = msgId
            };

            var msgStream = new MemoryStream();

            header.WriteTo(msgStream);
            msg.WriteTo(msgStream);

            var result = msgStream.ToArray();

            if (mUdpClient != null)
            {
                await mUdpClient.SendAsync(result, result.Length);
            }
        }