private void App_HeatBeat(Message message, UDPSession session)
        {
            Message msg = new Message(MessageType.HEARTBEAT);

            msg.SetMessageBody(session.SessionID);

            session.LastSessionTime = DateTime.Now;
            session.SendMessage(msg);

            SocketApplicationComm.Debug(string.Format("{0}发来心跳!", session.SessionID));
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            UDPSession session = new UDPSession();

            //session.Host = "127.0.0.1";
            //session.Port = 7777;
            while (true)
            {
                session.SendPackage(Encoding.Default.GetBytes("ddd_" + DateTime.Now.ToString()), "192.168.3.182", 7777);
                Console.ReadLine();
            }
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            var conn = new UDPSession();

            conn.Connect("127.0.0.1", 12345);
            Task.Run(() => {
                Read(conn);
            });
            Task.Run(() => {
                Write(conn);
            });
            Console.ReadLine();
        }
Ejemplo n.º 4
0
    public void StartWithSocket()
    {
        m_udpSession            = new UDPSession();
        m_udpSession.AckNoDelay = true;
        m_udpSession.WriteDelay = false;

        m_udpSession.Connect("127.0.0.1", 8090);
        Console.WriteLine("KCP 服务器夯起来,等待连接数据,ip:127.0.0.1,port:8090");

        //开启一个线程连接
        m_connectThread = new Thread(new ThreadStart(Receive));
        m_connectThread.Start();
    }
Ejemplo n.º 5
0
        private void App_LoginOut(Message message, UDPSession session)
        {
            Message msg = new Message(MessageType.LOGOUT);

            session.SendMessage(msg);
            lock (_sessiondic)
            {
                _sessiondic.Remove(session.SessionID);
            }
            session.IsValid = false;

            Console.WriteLine(string.Format("{0}已退出登陆", session.UserName));
        }
Ejemplo n.º 6
0
        protected override void FromSessionMessage(Message message, UDPSession session)
        {
            if (message.IsMessage((int)SOAMessageType.DoSOARedirectRequest))
            {
                try
                {
                    if (DoResponseAction != null)
                    {
                        var reqbag = LJC.FrameWork.EntityBuf.EntityBufCore.DeSerialize <SOARedirectRequest>(message.MessageBuffer);
                        var obj    = DoResponseAction(reqbag.FuncId, reqbag.Param, session.SessionID);

                        if (!string.IsNullOrWhiteSpace(message.MessageHeader.TransactionID))
                        {
                            var retmsg = new SocketApplication.Message((int)SOAMessageType.DoSOARedirectResponse);
                            retmsg.MessageHeader.TransactionID = message.MessageHeader.TransactionID;
                            SOARedirectResponse resp = new SOARedirectResponse();
                            resp.IsSuccess    = true;
                            resp.ResponseTime = DateTime.Now;
                            resp.Result       = LJC.FrameWork.EntityBuf.EntityBufCore.Serialize(obj);
                            retmsg.SetMessageBody(resp);

                            session.SendMessage(retmsg);
                        }
                        else
                        {
                            throw new Exception("服务未实现");
                        }
                    }
                }
                catch (Exception ex)
                {
                    var retmsg = new SocketApplication.Message((int)SOAMessageType.DoSOARedirectResponse);
                    retmsg.MessageHeader.TransactionID = message.MessageHeader.TransactionID;
                    SOARedirectResponse resp = new SOARedirectResponse();
                    resp.IsSuccess    = false;
                    resp.ResponseTime = DateTime.Now;
                    resp.ErrMsg       = ex.ToString();
                    retmsg.SetMessageBody(resp);

                    session.SendMessage(retmsg);
                }
            }
            else
            {
                base.FromSessionMessage(message, session);
            }
        }
Ejemplo n.º 7
0
 static void Write(UDPSession conn)
 {
     while (true)
     {
         var msg   = Encoding.UTF8.GetBytes(string.Format("hi, kcp {0:yyyy-MM-dd HH:mm:ss}", DateTime.Now));
         var count = conn.Send(msg, 0, msg.Length);
         if (count < 0)
         {
             Console.WriteLine("kcp write fail");
         }
         else
         {
             //Console.WriteLine("kcp write success", msg.ToString());
         }
         Thread.Sleep(1000);
     }
 }
Ejemplo n.º 8
0
    public void Connect(string ip, int port)
    {
        m_udpSession            = new UDPSession();
        m_udpSession.AckNoDelay = true;
        m_udpSession.WriteDelay = false;

        m_udpSession.Connect(ip, port);
        GameLog.Log("Connet to {0}:{1}", ip, port);
        //开启一个线程连接
        m_connectThread = new Thread(new ThreadStart(Receive));
        m_connectThread.Start();

        //定时器
        //Timer t = new Timer(100);//实例化Timer类,设置间隔时间为3000毫秒
        //t.Elapsed += new ElapsedEventHandler(SendToClient);//到达时间的时候执行事件
        //t.AutoReset = true;//设置是执行一次(false)还是一直执行(true)
        //t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件
    }
Ejemplo n.º 9
0
        protected sealed override void FromApp(Message message, IPEndPoint endpoint)
        {
            base.FromApp(message, endpoint);

            var        ipendpoint = ((IPEndPoint)endpoint);
            string     key        = string.Format("{0}_{1}", ipendpoint.Address.ToString(), ipendpoint.Port);
            UDPSession session    = null;

            if (_sessiondic.TryGetValue(key, out session))
            {
                if (message.IsMessage(MessageType.LOGOUT))
                {
                    App_LoginOut(message, session);
                }
                else if (message.IsMessage(MessageType.HEARTBEAT))
                {
                    App_HeatBeat(message, session);
                }
                else
                {
                    //if(!string.IsNullOrWhiteSpace(message.MessageHeader.TransactionID))
                    //{
                    //    Console.WriteLine("收到消息:" + message.MessageHeader.TransactionID);
                    //}

                    FromSessionMessage(message, session);
                }
            }
            else
            {
                if (message.IsMessage(MessageType.LOGIN))
                {
                    App_Login(message, new UDPSession {
                        SessionID = key, SessionServer = this, EndPoint = (IPEndPoint)endpoint
                    });
                }
                else
                {
                    Message msg = new Message(MessageType.RELOGIN);
                    SendMessage(msg, endpoint);
                    return;
                }
            }
        }
Ejemplo n.º 10
0
        static void Main(string[] args)
        {
            var connection = new UDPSession();

            connection.Connect("192.168.212.137", 4444);

            var firstSend = true;
            var buffer    = new byte[1024];
            var counter   = 0;

            while (true)
            {
                connection.Update();

                if (firstSend)
                {
                    //firstSend = false;
                    // Console.WriteLine("Write Message...");
                    var text = Encoding.UTF8.GetBytes(string.Format("Hello KCP: {0}", ++counter));
                    if (connection.Send(text, 0, text.Length) < 0)
                    {
                        Console.WriteLine("Write message failed.");
                        break;
                    }
                }

                var n = connection.Recv(buffer, 0, buffer.Length);
                if (n == 0)
                {
                    Thread.Sleep(10);
                    continue;
                }
                else if (n < 0)
                {
                    Console.WriteLine("Receive Message failed.");
                    break;
                }

                var resp = Encoding.UTF8.GetString(buffer, 0, n);
                Console.WriteLine("Received Message: " + resp);
            }
        }
Ejemplo n.º 11
0
        protected virtual void FromSessionMessage(Message message, UDPSession session)
        {
            if (message.IsMessage(MessageType.SENDFILE))
            {
                var sendfilemsg = LJC.FrameWork.EntityBuf.EntityBufCore.DeSerialize <SendFileMessage>(message.MessageBuffer);
                var dir         = AppDomain.CurrentDomain.BaseDirectory + "\\file\\";
                if (!System.IO.Directory.Exists(dir))
                {
                    System.IO.Directory.CreateDirectory(dir);
                }
                using (System.IO.FileStream fs = new System.IO.FileStream(dir + sendfilemsg.FileName, System.IO.FileMode.OpenOrCreate))
                {
                    fs.Position = fs.Length;
                    fs.Write(sendfilemsg.FileBytes, 0, sendfilemsg.FileBytes.Length);
                }

                Message sendfileecho = new Message(MessageType.SENDFILEECHO);
                sendfileecho.MessageHeader.TransactionID = message.MessageHeader.TransactionID;
                sendfileecho.SetMessageBody(new SendFileECHOMessage
                {
                    IsSuccess = true
                });
                SendMessage(sendfileecho, session.EndPoint);
            }
            else if (message.IsMessage(MessageType.SENDFILRESENDCHECK))
            {
                var request   = LJC.FrameWork.EntityBuf.EntityBufCore.DeSerialize <SendFileCheckRequestMessage>(message.MessageBuffer);
                var dir       = AppDomain.CurrentDomain.BaseDirectory + "\\file\\";
                var fileinofo = new System.IO.FileInfo(dir + request.FileName);
                var len       = 0L;
                if (fileinofo.Exists)
                {
                    len = fileinofo.Length;
                }
                Message response = new Message(MessageType.SENDFILRESENDCHECK);
                response.MessageHeader.TransactionID = message.MessageHeader.TransactionID;
                response.SetMessageBody(new SendFileCheckResponseMessage {
                    FileLength = len, FileName = request.FileName
                });
                SendMessage(response, session.EndPoint);
            }
        }
Ejemplo n.º 12
0
        static void Main(string[] args)
        {
            while (true)
            {
                UDPSession session = new UDPSession();
                session.OnDataReceived += Session_OnDataReceived;
                DBTransfer transfer = new DBTransfer();
                transfer.DBServerType = DBServerType.ServerSQL;
                transfer.SQL          = "select * from Student";
                transfer.RequestID    = 0;//异步处理可以辨别
                transfer.IsQuery      = true;
                // transfer.DBCfg = "XXXX";//服务端SQL支持多数据库,以配置文件名称区分调用的;不配置即是服务端默认值
                //transfer.IsScala = false;
                //transfer.IsModel = true;
                //transfer.ModelCls = "xxxxx.xxx";
                //transfer.ModelDLL = "xxx.dll";
                byte[] req = SerializerFactory <CommonSerializer> .Serializer(transfer);

                session.SendPackage(req, "127.0.0.1", 7777);
                Console.ReadLine();
            }
        }
Ejemplo n.º 13
0
        protected Client(Region region, Environment environment = Environment.Production)
        {
            _region = region;
            _env    = environment;

            _connected               = false;
            _heartbeatInterval       = TimeSpan.FromSeconds(1);
            _lastHeartbeat           = DateTime.UtcNow;
            _udpSession              = new UDPSession();
            _sessionId               = 0;
            _sendBuffer              = new byte[c_sendBufferSize];
            _recvBuffer              = new byte[c_recvBufferSize];
            _sendBufferLen           = 0;
            _recvBufferLen           = 0;
            _recvBufferStatus        = 0;
            _recvBufferPayloadLen    = 0;
            _recvBufferPayloadRemain = 0;
            _failedCount             = 0;

            _centralClient = new Central.Client(_region, _env);
            _controller    = new Controller();
        }
Ejemplo n.º 14
0
        static void Read(UDPSession conn)
        {
            var buf = new byte[1024];

            while (true)
            {
                var count = conn.Recv(buf, 0, buf.Length);
                if (count < 0)
                {
                    Console.WriteLine("kcp read fail");
                    continue;
                }
                else if (count == 0)
                {
                }
                else
                {
                    var msg = Encoding.UTF8.GetString(buf, 0, count);
                    Console.WriteLine("kcp read success: {0}, {1}", count, msg);
                    Thread.Sleep(1000);
                }
            }
        }
Ejemplo n.º 15
0
 protected override void FromSessionMessage(Message message, UDPSession session)
 {
     base.FromSessionMessage(message, session);
 }
Ejemplo n.º 16
0
        //sends the packet and deletes it when done (if successful).rv :true success
        public override bool send(netHeader.NetPacket pkt)
        {
            bool result = false;

            PacketReader.EthernetFrame ef = new PacketReader.EthernetFrame(pkt);

            switch (ef.Protocol)
            {
            case (int)EtherFrameType.NULL:
                //Adapter Reset
                //TODO close all open connections
                break;

            case (int)EtherFrameType.IPv4:
                //Console.Error.WriteLine("IPv4");
                IPPacket ippkt = ((IPPacket)ef.Payload);
                if (ippkt.VerifyCheckSum() == false)
                {
                    Console.Error.WriteLine("IP packet with bad CSUM");
                }
                if (ippkt.Payload.VerifyCheckSum(ippkt.SourceIP, ippkt.DestinationIP) == false)
                {
                    Console.Error.WriteLine("IP packet with bad Payload CSUM");
                }

                string Key = (ippkt.DestinationIP[0]) + "." + (ippkt.DestinationIP[1]) + "." + (ippkt.DestinationIP[2]) + "." + ((UInt64)ippkt.DestinationIP[3])
                             + "-" + (ippkt.Protocol);

                switch (ippkt.Protocol)     //(Prase Payload)
                {
                case (byte)IPType.ICMP:
                    Console.Error.WriteLine("ICMP");
                    lock (sentry)
                    {
                        if (Connections.ContainsKey(Key))
                        {
                            if (Connections[Key].isOpen() == false)
                            {
                                throw new Exception("Attempt to send on Closed Connection");
                            }
                            Console.Error.WriteLine("Found Open Connection");
                            result = Connections[Key].send(ippkt.Payload);
                        }
                        else
                        {
                            Console.Error.WriteLine("Creating New Connection with key " + Key);
                            ICMPSession s = new ICMPSession();
                            s.DestIP   = ippkt.DestinationIP;
                            s.SourceIP = UDP_DHCPsession.PS2_IP;
                            result     = s.send(ippkt.Payload);
                            Connections.Add(Key, s);
                        }
                    }
                    break;

                case (byte)IPType.TCP:
                    //Console.Error.WriteLine("TCP");
                    TCP tcp = (TCP)ippkt.Payload;

                    Key += "-" + ((UInt64)tcp.SourcePort) + ":" + ((UInt64)tcp.DestinationPort);
                    lock (sentry)
                    {
                        if (Connections.ContainsKey(Key))
                        {
                            if (Connections[Key].isOpen() == false)
                            {
                                throw new Exception("Attempt to send on Closed TCP Connection of Key : " + Key + "");
                            }
                            //Console.Error.WriteLine("Found Open Connection");
                            result = Connections[Key].send(ippkt.Payload);
                        }
                        else
                        {
                            //Console.Error.WriteLine("Creating New Connection with key " + Key);
                            Console.Error.WriteLine("Creating New TCP Connection with Dest Port " + tcp.DestinationPort);
                            TCPSession s = new TCPSession();
                            s.DestIP   = ippkt.DestinationIP;
                            s.SourceIP = UDP_DHCPsession.PS2_IP;
                            result     = s.send(ippkt.Payload);
                            Connections.Add(Key, s);
                        }
                    }
                    break;

                case (byte)IPType.UDP:
                    //Console.Error.WriteLine("UDP");
                    UDP udp = (UDP)ippkt.Payload;

                    Key += "-" + ((UInt64)udp.SourcePort) + ":" + ((UInt64)udp.DestinationPort);
                    if (udp.DestinationPort == 67)
                    {         //DHCP
                        result = DCHP_server.send(ippkt.Payload);
                        break;
                    }
                    lock (sentry)
                    {
                        if (Connections.ContainsKey(Key))
                        {
                            if (Connections[Key].isOpen() == false)
                            {
                                throw new Exception("Attempt to send on Closed Connection");
                            }
                            //Console.Error.WriteLine("Found Open Connection");
                            result = Connections[Key].send(ippkt.Payload);
                        }
                        else
                        {
                            //Console.Error.WriteLine("Creating New Connection with key " + Key);
                            Console.Error.WriteLine("Creating New UDP Connection with Dest Port " + udp.DestinationPort);
                            UDPSession s = new UDPSession();
                            s.DestIP   = ippkt.DestinationIP;
                            s.SourceIP = UDP_DHCPsession.PS2_IP;
                            result     = s.send(ippkt.Payload);
                            Connections.Add(Key, s);
                        }
                    }
                    break;

                default:
                    Console.Error.WriteLine("Unkown Protocol");
                    //throw new NotImplementedException();
                    break;
                }
                //Console.Error.WriteLine("Key = " + Key);
                break;

                #region "ARP"
            case (int)EtherFrameType.ARP:
                Console.Error.WriteLine("ARP (Ignoring)");
                ARPPacket arppkt = ((ARPPacket)ef.Payload);

                ////Detect ARP Packet Types
                //if (Utils.memcmp(arppkt.SenderProtocolAddress, 0, new byte[] { 0, 0, 0, 0 }, 0, 4))
                //{
                //    Console.WriteLine("ARP Probe"); //(Who has my IP?)
                //    break;
                //}
                //if (Utils.memcmp(arppkt.SenderProtocolAddress, 0, arppkt.TargetProtocolAddress, 0, 4))
                //{
                //    if (Utils.memcmp(arppkt.TargetHardwareAddress, 0, new byte[] { 0, 0, 0, 0, 0, 0 }, 0, 6) & arppkt.OP == 1)
                //    {
                //        Console.WriteLine("ARP Announcement Type 1");
                //        break;
                //    }
                //    if (Utils.memcmp(arppkt.SenderHardwareAddress, 0, arppkt.TargetHardwareAddress, 0, 6) & arppkt.OP == 2)
                //    {
                //        Console.WriteLine("ARP Announcement Type 2");
                //        break;
                //    }
                //}

                ////if (arppkt.OP == 1) //ARP request
                ////{
                ////    //This didn't work for whatever reason.
                ////    if (Utils.memcmp(arppkt.TargetProtocolAddress,0,UDP_DHCPsession.GATEWAY_IP,0,4))
                ////    //it's trying to resolve the virtual gateway's mac addr
                ////    {
                ////        Console.Error.WriteLine("ARP Attempt to Resolve Gateway Mac");
                ////        arppkt.TargetHardwareAddress = arppkt.SenderHardwareAddress;
                ////        arppkt.SenderHardwareAddress = gateway_mac;
                ////        arppkt.TargetProtocolAddress = arppkt.SenderProtocolAddress;
                ////        arppkt.SenderProtocolAddress = UDP_DHCPsession.GATEWAY_IP;
                ////        arppkt.OP = 2;

                ////        EthernetFrame retARP = new EthernetFrame(arppkt);
                ////        retARP.DestinationMAC = ps2_mac;
                ////        retARP.SourceMAC = gateway_mac;
                ////        retARP.Protocol = (Int16)EtherFrameType.ARP;
                ////        vRecBuffer.Add(retARP.CreatePacket());
                ////        break;
                ////    }
                ////}
                //Console.Error.WriteLine("Unhandled ARP packet");

                result = true;
                break;

                #endregion
            case (int)0x0081:
                Console.Error.WriteLine("VLAN-tagged frame (IEEE 802.1Q)");
                throw new NotImplementedException();

            //break;
            default:
                Console.Error.WriteLine("Unkown EtherframeType " + ef.Protocol.ToString("X4"));
                break;
            }

            return(result);
        }
Ejemplo n.º 17
0
        static void Main(string[] args)
        {
            var connection = new UDPSession();

            connection.AckNoDelay = true;
            connection.WriteDelay = false;

            connection.Connect("127.0.0.1", 4444);

            var stopSend  = false;
            var buffer    = new byte[1500];
            var counter   = 0;
            var sendBytes = 0;
            var recvBytes = 0;

            while (true)
            {
                connection.Update();

                if (!stopSend)
                {
                    //firstSend = false;
                    // Console.WriteLine("Write Message...");
                    //var text = Encoding.UTF8.GetBytes(string.Format("Hello KCP: {0}", ++counter));
                    var sent = connection.Send(buffer, 0, buffer.Length);
                    if (sent < 0)
                    {
                        Console.WriteLine("Write message failed.");
                        break;
                    }

                    if (sent > 0)
                    {
                        counter++;
                        sendBytes += buffer.Length;
                        if (counter >= 500)
                        {
                            stopSend = true;
                        }
                    }
                }

                var n = connection.Recv(buffer, 0, buffer.Length);
                if (n == 0)
                {
                    Thread.Sleep(10);
                    continue;
                }
                else if (n < 0)
                {
                    Console.WriteLine("Receive Message failed.");
                    break;
                }
                else
                {
                    recvBytes += n;
                    Console.WriteLine($"{recvBytes} / {sendBytes}");
                }

                //var resp = Encoding.UTF8.GetString(buffer, 0, n);
                //Console.WriteLine("Received Message: " + resp);
            }
        }
Ejemplo n.º 18
0
        static void Main(string[] args)
        {
            var connection = new UDPSession();

            connection.Connect("10.0.2.156", 7788); // 服务器
                                                    //            connection.Connect("10.0.18.57", 7788);// 吴宇

            var firstSend = true;
            var buffer    = new byte[1024 * 32];
            var counter   = 0;

            UDPStatus lUDPStatus = UDPStatus.eUDPStatus_CONNECT_REQ;

            bool waitTransmit = false;

            while (true)
            {
                connection.Update();

                switch (lUDPStatus)
                {
                case UDPStatus.eUDPStatus_CONNECT_REQ:
                {
                    if (connection.ConnectUDP() < 0)
                    {
                        Console.WriteLine("Write message failed.");
                        break;
                    }
                    lUDPStatus = UDPStatus.eUDPStatus_CONNECTING;
                }
                break;

                case UDPStatus.eUDPStatus_CONNECTING:
                {
                    var n = connection.RecvUDP(buffer, 0, buffer.Length);

                    if (n == 0)
                    {
                        Thread.Sleep(10);
                        continue;
                    }
                    else if (n < 0)
                    {
                        Console.WriteLine("Receive Message failed.");
                        break;
                    }
                    else
                    {
                        UDPProtocolConnectRsp rsp = UDPSession.ByteToStructure <UDPProtocolConnectRsp>(buffer);
                        if (rsp != null)
                        {
                            if (connection.CheckConv(rsp.conv))
                            {
                                if (rsp.p_type == (int)UDPStatus.eUDPStatus_CONNECT_RSP)
                                {
                                    lUDPStatus = UDPStatus.eUDPStatus_CONNECTED;
                                    Console.WriteLine("Connect Success");
                                }
                            }
                            else
                            {
                                lUDPStatus = UDPStatus.eUDPStatus_UNKNOWN;
                                Console.WriteLine("Session Conv Error");
                                break;
                            }
                        }
                    }
                }
                break;

                case UDPStatus.eUDPStatus_CONNECTED:
                case UDPStatus.eUDPStatus_KEEP_LIVE:
                {
                    bool live = false;

                    connection.SendKeepLive();
                    connection.TestTransimitKCP();

                    UDPStatus n = connection.RecvKcp(buffer, 0, buffer.Length);
                    switch (n)
                    {
                    case UDPStatus.eUDPStatus_KEEP_LIVE:
                    {
                        keepLiveCount++;
                        Console.WriteLine("KeepLive:" + keepLiveCount);
                        lUDPStatus = UDPStatus.eUDPStatus_KEEP_LIVE;
                        live       = true;
                    }
                    break;

                    case UDPStatus.eUDPStatus_TRANSMIT:
                    {
                        GameProtocol data = UDPSession.ByteToStructure <GameProtocol>(buffer);
                        if (data != null)
                        {
                            Console.WriteLine("TestTransimit............ receive data : " + data.data);
                            live = true;
                        }
                        waitTransmit = false;
                    }
                    break;
                    }

                    if (live)
                    {
                        liveCount = 0;
                    }
                    else
                    {
                        liveCount++;
//                                Thread.Sleep(1000);
                    }

                    if (liveCount > 5)
                    {
//                                lUDPStatus = UDPStatus.eUDPStatus_DISCONNECT;
                    }

                    //                            int rn = 0;
                    //                            if (lUDPStatus == UDPStatus.eUDPStatus_KEEP_LIVE)
                    //                            {
                    //                                if (!waitTransmit)
                    //                                {
                    //                                    rn = connection.TestTransimitKCP();
                    //                                    waitTransmit = true;
                    //                                    if (rn < 0)
                    //                                    {
                    //                                        Console.WriteLine("TestTransimit............failed !!!!!.");
                    //                                    }
                    //                                    else if (rn > 0)
                    //                                    {
                    //                                        var n = connection.RecvUDP(buffer, 0, buffer.Length);
                    //                                        if (n > 0)
                    //                                        {
                    //                                            UDPProtocolTransmit transmit = UDPSession.ByteToStructure<UDPProtocolTransmit>(buffer);
                    //                                            if (transmit != null &&
                    //                                                connection.CheckConv(transmit.conv) &&
                    //                                                transmit.p_type == (int)UDPStatus.eUDPStatus_TRANSMIT)
                    //                                            {
                    //                                                Console.WriteLine("TestTransimit............ receive data : " + transmit);
                    //                                            }
                    //                                        }
                    //                                    }
                    //                                }
                    //                                else
                    //                                {
                    //                                    var n = connection.RecvUDP(buffer, 0, buffer.Length);
                    //                                    if (n > 0)
                    //                                    {
                    //                                        UDPProtocolTransmit transmit = UDPSession.ByteToStructure<UDPProtocolTransmit>(buffer);
                    //                                        if (transmit != null &&
                    //                                            connection.CheckConv(transmit.conv) &&
                    //                                            transmit.p_type == (int)UDPStatus.eUDPStatus_TRANSMIT)
                    //                                        {
                    //                                            Console.WriteLine("TestTransimit............ receive.");
                    //                                            waitTransmit = false;
                    //                                        }
                    //                                    }
                    //                                }
                    //                            }

                    /////////////////////////////////////////////////////////////////
                    //                            Thread.Sleep(1100);
                    //                            rn = connection.SendKeepLive();
                    //                            if (rn < 0)
                    //                            {
                    //                                Console.WriteLine("Write message failed.");
                    //                                break;
                    //                            }
                    //                            else if (rn > 0)
                    //                            {
                    //                                Thread.Sleep(10);
                    //                                var n = connection.RecvUDP(buffer, 0, buffer.Length);
                    //                                if (n > 0)
                    //                                {
                    //                                    UDPProtocolKeepLive keepLive =
                    //                                        UDPSession.ByteToStructure<UDPProtocolKeepLive>(buffer);
                    //                                    if (keepLive != null &&
                    //                                        connection.CheckConv(keepLive.conv) &&
                    //                                        keepLive.p_type == (int)UDPStatus.eUDPStatus_KEEP_LIVE)
                    //                                    {
                    //                                        lUDPStatus = UDPStatus.eUDPStatus_KEEP_LIVE;
                    //                                        keepLiveCount++;
                    //                                        Console.WriteLine("KeepLive:" + keepLiveCount);
                    //                                        break;
                    //                                    }
                    //                                }
                    //                            }

                    //                            int checkNum = 0;
                    //                            for (int i = 0; i < 5; i++)
                    //                            {
                    //                                Thread.Sleep(1000);
                    //                                rn = connection.SendKeepLive();
                    //                                if (rn < 0)
                    //                                {
                    //                                    Console.WriteLine("Write message failed.");
                    //                                    checkNum++;
                    //                                    continue;
                    //                                }
                    //                                else if (rn > 0)
                    //                                {
                    //                                    Thread.Sleep(10);
                    //                                    var n = connection.RecvUDP(buffer, 0, buffer.Length);
                    //                                    if (n > 0)
                    //                                    {
                    //                                        UDPProtocolKeepLive keepLive =
                    //                                            UDPSession.ByteToStructure<UDPProtocolKeepLive>(buffer);
                    //                                        if (keepLive != null &&
                    //                                            connection.CheckConv(keepLive.conv) &&
                    //                                            keepLive.p_type == (int)UDPStatus.eUDPStatus_KEEP_LIVE)
                    //                                        {
                    //                                            keepLiveCount++;
                    //                                            Console.WriteLine("KeepLive:" + keepLiveCount);
                    //                                            break;
                    //                                        }
                    //                                    }
                    //                                    checkNum++;
                    //                                    continue;
                    //                                }
                    //                                checkNum++;
                    //                            }
                    //
                    //                            if (checkNum > 4)
                    //                            {
                    //                                                                lUDPStatus = UDPStatus.eUDPStatus_DISCONNECT;
                    //                            }
                }
                break;

                case UDPStatus.eUDPStatus_DISCONNECT:
                {
                    Console.WriteLine("DISCONNECT");
                    lUDPStatus = UDPStatus.eUDPStatus_DEAD;
                }
                break;

                case UDPStatus.eUDPStatus_DEAD:
                    break;
                }

                //
                //                if (firstSend)  {
                //                    //firstSend = false;
                //                    // Console.WriteLine("Write Message...");
                //                    var text = Encoding.UTF8.GetBytes(string.Format("Hello KCP: {0}", ++counter));
                //                    if (connection.Send(text, 0, text.Length) < 0) {
                //                        Console.WriteLine("Write message failed.");
                //                        break;
                //                    }
                //                }
                //
                //                var n = connection.Recv(buffer, 0, buffer.Length);
                //                if (n == 0) {
                //                    Thread.Sleep(10);
                //                    continue;
                //                } else if (n < 0) {
                //                    Console.WriteLine("Receive Message failed.");
                //                    break;
                //                }
                //
                //                var resp = Encoding.UTF8.GetString(buffer, 0, n);
                //                Console.WriteLine("Received Message: " + resp);
            }
        }
Ejemplo n.º 19
0
        private void App_Login(Message message, UDPSession session)
        {
            Exception           ex      = null;
            LoginRequestMessage request = message.GetMessageBody <LoginRequestMessage>();
            //string uid = message.Get<string>(FieldEnum.LoginID);
            //string pwd = message.Get<string>(FieldEnum.LoginPwd);

            Message LoginSuccessMessage      = new Message(MessageType.LOGIN);
            LoginResponseMessage responsemsg = new LoginResponseMessage();

            string loginFailMsg = string.Empty;
            bool   canLogin     = false;

            try
            {
                canLogin = OnUserLogin(request.LoginID, request.LoginPwd, out loginFailMsg);
            }
            catch (Exception e)
            {
                ex           = e;
                loginFailMsg = "服务器出错";
            }
            if (canLogin)
            {
                responsemsg.LoginResult = true;
                session.IsLogin         = true;
                session.UserName        = request.LoginID;

                //session.Socket = s;
                //session.IPAddress = ((System.Net.IPEndPoint)s.RemoteEndPoint).Address.ToString();
                lock (_sessiondic)
                {
                    if (_sessiondic.ContainsKey(session.SessionID))
                    {
                        _sessiondic.Remove(session.SessionID);
                    }
                    _sessiondic.Add(session.SessionID, session);
                }
                Console.WriteLine("{0}成功登陆", request.LoginID);
            }
            else
            {
                responsemsg.LoginResult = false;
            }

            string heartBeatConfig = ConfigHelper.AppConfig("HeartBeat");
            //int headBeatInt = int.Parse(ConfigurationManager.AppSettings["HeartBeat"]);
            int headBeatInt;

            if (!int.TryParse(heartBeatConfig, out headBeatInt))
            {
                headBeatInt = 5000;
            }

            responsemsg.SessionID        = session.SessionID;
            responsemsg.LoginID          = request.LoginID;
            responsemsg.HeadBeatInterVal = headBeatInt;
            responsemsg.SessionTimeOut   = headBeatInt * 3;
            responsemsg.LoginFailReson   = loginFailMsg;
            LoginSuccessMessage.SetMessageBody(responsemsg);
            session.SendMessage(LoginSuccessMessage);
            //SendMessage(LoginSuccessMessage, session.EndPoint,session.SendMsgFlag);

            if (!canLogin)
            {
                session.Close();
                Console.WriteLine("{0}登录失败", request.LoginID);
            }

            if (ex != null)
            {
                throw ex;
            }
        }
Ejemplo n.º 20
0
        static void Main(string[] args)
        {
            var salt         = "demo salt";
            var password     = "******";
            var interactions = 1024;


            var df       = new Rfc2898DeriveBytes(password, Encoding.UTF8.GetBytes(salt), interactions);
            var key      = df.GetBytes(32);
            var aes      = new AesBlockCrypt(key);
            var checksum = Crc32Algorithm.Compute(new byte[] { 0, 0, 0, 0, 1, 2, 3, 4, 5, 6 }, 4, 10 - 4);

            Console.WriteLine(checksum);
            var connection = new UDPSession();

            connection.Connect("192.168.1.29", 10000, aes);
            Console.WriteLine("begin udpsession kcp");

            var firstSend = true;
            var buffer    = new byte[1024];
            var counter   = 0;

            DateTime resetTime = DateTime.Now;

            while (true)
            {
                if (!connection.IsConnected)
                {
                    Console.WriteLine("断开连接");
                    Thread.Sleep(1000);
                    connection.Close();
                    connection.Connect("192.168.1.29", 10000, aes);
                    continue;
                }
                connection.Update();


                var cur = DateTime.Now.Subtract(resetTime);
                if (firstSend && cur.TotalMilliseconds > 0)
                {
                    resetTime = DateTime.Now;
                    //firstSend = false;
                    // Console.WriteLine("Write Message...");
                    var text = Encoding.UTF8.GetBytes(string.Format("Hello KCP: {0}", ++counter));
                    if (connection.Send(text, 0, text.Length) < 0)
                    {
                        Console.WriteLine("Write message failed.");
                        break;
                    }

                    Thread.Sleep(10);
                }

                var n = connection.Recv(buffer, 0, buffer.Length);
                if (n == 0)
                {
                    Thread.Sleep(10);
                    continue;
                }
                else if (n < 0)
                {
                    Console.WriteLine("Receive Message failed.");
                    break;
                }

                var resp = Encoding.UTF8.GetString(buffer, 0, n);
                Console.WriteLine("Received Message: " + resp);
            }
        }
Ejemplo n.º 21
0
        public bool SendUDP(ConnectionKey Key, IPPacket ipPkt)
        {
            Log_Verb("UDP");
            UDP udp = (UDP)ipPkt.Payload;

            Key.PS2Port = udp.SourcePort; Key.SRVPort = udp.DestinationPort;

            if (udp.DestinationPort == 67)
            { //DHCP
                return(dhcpServer.Send(ipPkt.Payload));
            }

            if (udp.DestinationPort == 53 && Utils.memcmp(ipPkt.DestinationIP, 0, DefaultDHCPConfig.DHCP_IP, 0, 4))
            { //DNS
                return(dnsServer.Send(ipPkt.Payload));
            }

            int res = SendFromConnection(Key, ipPkt);

            if (res == 1)
            {
                return(true);
            }
            else if (res == 0)
            {
                return(false);
            }
            else
            {
                Log_Verb("Creating New Connection with key " + Key);
                Log_Info("Creating New UDP Connection with Dest Port " + udp.DestinationPort);
                UDPSession s;
                if (udp.SourcePort == udp.DestinationPort ||                                 //Used for LAN games that assume the destination port
                    Utils.memcmp(ipPkt.DestinationIP, 0, dhcpServer.Broadcast, 0, 4) ||
                    Utils.memcmp(ipPkt.DestinationIP, 0, dhcpServer.LimitedBroadcast, 0, 4)) //Broadcast packets
                {
                    //Limit of one udpclient per local port
                    //need to reuse the udpclient
                    UDPFixedPort fPort;
                    if (fixedUDPPorts.ContainsKey(udp.SourcePort))
                    {
                        Log_Verb("Using Existing UDPFixedPort");
                        fPort = fixedUDPPorts[udp.SourcePort];
                    }
                    else
                    {
                        ConnectionKey fKey = new ConnectionKey
                        {
                            Protocol = (byte)IPType.UDP,
                            PS2Port  = udp.SourcePort,
                            SRVPort  = 0
                        };

                        Log_Verb("Creating New UDPFixedPort with key " + fKey);
                        Log_Info("Creating New UDPFixedPort with Port " + udp.SourcePort);

                        fPort = new UDPFixedPort(fKey, adapterIP, udp.SourcePort);
                        fPort.ConnectionClosedEvent += HandleFixedPortClosed;

                        fPort.DestIP   = new byte[] { 0, 0, 0, 0 };
                        fPort.SourceIP = dhcpServer.PS2IP;

                        if (!connections.TryAdd(fKey, fPort) |
                            !fixedUDPPorts.TryAdd(udp.SourcePort, fPort))
                        {
                            fPort.Dispose();
                            throw new Exception("Connection Add Failed");
                        }
                    }
                    s = fPort.NewClientSession(Key, Utils.memcmp(ipPkt.DestinationIP, 0, dhcpServer.Broadcast, 0, 4) |
                                               Utils.memcmp(ipPkt.DestinationIP, 0, dhcpServer.LimitedBroadcast, 0, 4));
                }
                else
                {
                    s = new UDPSession(Key, adapterIP);
                }
                s.ConnectionClosedEvent += HandleConnectionClosed;
                s.DestIP   = ipPkt.DestinationIP;
                s.SourceIP = dhcpServer.PS2IP;
                if (!connections.TryAdd(Key, s))
                {
                    throw new Exception("Connection Add Failed");
                }
                return(s.Send(ipPkt.Payload));
            }
        }