예제 #1
0
 public void BlockingDisconnect(int timeout)
 {
     try
     {
         this.Session.BlockingDisconnect(timeout);
         this.Session = null;
     }
     catch (Exception e)
     {
         if (ExceptionHandler != null)
             ExceptionHandler(e);
     }
 }
예제 #2
0
 public void Disconnect()
 {
     try
     {
         this.Session.Disconnect();
         this.Session = null;
     }
     catch (Exception e)
     {
         if (ExceptionHandler != null)
             ExceptionHandler(e);
     }
 }
예제 #3
0
파일: SGIPClient.cs 프로젝트: tommybiteme/X
        /// <summary>登录。发送Bind指令,接收Bind_Resp响应</summary>
        /// <returns></returns>
        public Boolean Login()
        {
            WriteLog(String.Format("正在连接服务器…… {0}:{1}", IP, Port));
            var client = new TcpSession();
            Client = client;
            try
            {
                //client.Connect(IP, Port);
                //client.Connect(IP, Port);
                client.Remote.Host = IP;
                client.Remote.Port = Port;
            }
            catch (Exception ex)
            {
                String str = IP + ":" + Port.ToString();
                throw new NetException("连接网关服务器" + str + "出错,请确定网络是否畅通!" + ex.Message, ex);
            }

            var cmd = new SGIPBind();
            cmd.LoginName = SystemID;
            cmd.LoginPassowrd = Password;
            cmd.LoginType = LoginTypes.SpToSmg;

            WriteLog("正在登录……");

            var session = client as ISocketSession;
            session.Send(cmd.GetStream());
            var data = client.Receive();
            var resp = SGIPEntity.Read(new MemoryStream(data)) as SGIPResponse;

            if (resp == null) throw new Exception("登录失败!服务器没有响应!");
            if (resp.Result != SGIPErrorCodes.Success) throw new Exception("登录失败!" + resp.Result.GetDescription());

            //登录完成,开始读取指令
            client.Received += Client_Received;
            client.ReceiveAsync();

            Logined = true;

            WriteLog("登录成功!");

            return true;
        }
예제 #4
0
        static void Main(string[] args)
        {
            var dispatcher = SimpleDispatcher.CurrentDispatcher;
            var serializer = new MessageSerializer();
            serializer.Register<Message>();
            serializer.Register<string>();
            HashSet<TcpSession> sessions = new HashSet<TcpSession>();

            // 初始化service
            var service = new MessageTcpService(serializer, (session, o) =>
            {
                dispatcher.Invoke(() =>
                {
                    session.Send(o);
                });
            },
            () =>
            {
                var session = new TcpSession();
                Console.WriteLine("connected");
                sessions.Add(session);
                session.Disconnected += (e) =>
                {
                    Console.WriteLine("Disconnected:" + e.Message);
                    sessions.Remove(session);
                };
                return session;
            });
            service.MessageDeserializeFailed += (e) => { Console.WriteLine(e.Message); };
            var ip = IPAddress.Any;
            service.Listen(new IPEndPoint(ip, 9528));
            var timer = new Eddy.Timers.Timer();
            timer.Tick += () =>
            {
                Console.WriteLine("{0} clients connected.", sessions.Count);
            };
            timer.Interval = new TimeSpan(0, 0, 5);
            timer.Start();
            dispatcher.Run();
        }
예제 #5
0
        private void HandleSetDataRequest(TcpSession session, Packet p)
        {
            //_logger.Debug("-C_SETDATA_REQ-");

            Player plr;

            if (!_players.TryGetValue(session.Guid, out plr))
            {
                session.StopListening();
                return;
            }

            p.ReadUInt16(); // unk
            p.ReadUInt64(); // accID
            plr.ServerID = p.ReadUInt16();
            var channelID = p.ReadInt16();
            var roomID    = p.ReadInt32();

            if (roomID == -1)
            {
                roomID = 0;
            }
            if (channelID == -1)
            {
                channelID = 0;
            }

            plr.Room = new Room(null, EServerType.Chat)
            {
                ID = (uint)roomID
            };
            plr.CommunityByte = p.ReadByte();
            p.ReadUInt32();  // total exp
            p.ReadBytes(32); // td/dm info

            plr.AllowCombiRequest  = (EAllowCommunityRequest)p.ReadByte();
            plr.AllowFriendRequest = (EAllowCommunityRequest)p.ReadByte();
            plr.AllowInvite        = (EAllowCommunityRequest)p.ReadByte();
            plr.AllowInfoRequest   = (EAllowCommunityRequest)p.ReadByte();

            plr.CommunityData = p.ReadBytes(41);

            Channel channel;

            if (!_channels.TryGetValue((ushort)channelID, out channel))
            {
                return;
            }
            if (plr.Channel == null && channelID > 0) // join
            {
                var ack = new Packet(EChatPacket.SChannelPlayerListInfoAck);
                ack.Write((uint)channel.ID);
                ack.Write(channel.Players.Count);
                foreach (var player in channel.Players.Values)
                {
                    ack.WriteChatUserData(player);
                }

                session.Send(ack);
                channel.Join(plr);
            }
            else if (channelID == 0) // leave
            {
                if (plr.Channel != null)
                {
                    plr.Channel.Leave(plr);
                }
            }
            else // update
            {
                var ack = new Packet(EChatPacket.SChannelPlayerListInfoAck);
                ack.Write((uint)channel.ID);
                ack.Write(channel.Players.Count);
                foreach (var player in channel.Players.Values)
                {
                    ack.WriteChatUserData(player);
                }

                channel.Broadcast(ack);
            }
        }
예제 #6
0
 protected override void OnDisconnected(TcpSession session)
 {
     sessions.Remove((ChatSession)session);
     base.OnDisconnected(session);
 }
예제 #7
0
        private bool tcpServer_SessionReceived(TcpSession session, byte[] data)
        {
            if (!session.IsHandshaked)
            {
                // from tablet:

                /*
                 * GET /Typhoon HTTP/1.1
                 * Upgrade: WebSocket
                 * Connection: Upgrade
                 * Host: 192.168.0.102:2013
                 * Origin: http://192.168.0.102:81
                 * Sec-Websocket-Key: +d6dlnAp7rrQ3otS7Zvi7g==
                 * Sec-WebSocket-Version: 13
                 +d6dlnAp7rrQ3otS7Zvi7g==: websocket
                 +d6dlnAp7rrQ3otS7Zvi7g==: Upgrade
                 */

                // from local:

                /*
                 * GET /Typhoon HTTP/1.1
                 * Upgrade: WebSocket
                 * Connection: Upgrade
                 * Host: localhost:2013
                 * Origin: http://localhost:81
                 * Sec-Websocket-Key: K92AZtSFpS+9OgiwcPMheg==
                 * Sec-WebSocket-Version: 13
                 * K92AZtSFpS+9OgiwcPMheg==: websocket
                 * K92AZtSFpS+9OgiwcPMheg==: x-webkit-deflate-frame
                 * K92AZtSFpS+9OgiwcPMheg==: Upgrade
                 */

                // location: ws://localhost:2013
                // origin: "http://localhost:81"

                WSClientHandshake chs = WSClientHandshake.FromBytes(data);
                //if (chs.IsValid && "ws://" + chs.Host == location && chs.Origin == origin)
                //if (chs.IsValid && "ws://" + chs.Host == location)
                if (chs.IsValid)
                {
                    WSServerHandshake shs          = new WSServerHandshake(chs.Key);
                    string            stringShake  = shs.ToString();
                    byte[]            byteResponse = Encoding.UTF8.GetBytes(stringShake);
                    session.Send(byteResponse);
                    session.IsHandshaked = true;

                    // for debug:
                    //client.Send(WebSocketDataFrame.WrapString("Hello from server!!!"));

                    return(false);
                }
                else
                {
                    return(true); // disconnect client
                }
            }
            else
            {
                WSDataFrame frame   = new WSDataFrame(data);
                byte[]      payload = null;
                if (frame.IsValid() && frame.FIN)
                {
                    payload = frame.GetPayload();
                }

                // for debug:
                //string s = new string(Encoding.UTF8.GetChars(payload));
                //string b = "";
                //b += s;

                return(SessionDataReceived != null?SessionDataReceived(session, payload) : false);
            }
        }
예제 #8
0
 public PacketReceivedEventArgs(TcpSession session, Packet packet)
 {
     Session = session;
     Packet = packet;
 }
예제 #9
0
 public TcpComponent()
 {
     tcpSession = new TcpSession();
 }
예제 #10
0
 public PacketReceivedEventArgs(TcpSession session, Packet packet)
 {
     Session = session;
     Packet  = packet;
 }
예제 #11
0
 protected BusinessHandlerBase(TcpSession tcpSession)
 {
     this.tcpSession = tcpSession;
 }
		public override void Open (ConnectionOptions options)
		{
			Socket socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			bool useRoundRobin = options.RoundRobin;
			int hostIndex = 0;
			int startIndex = 0;

	                charset_utf8 = (options.Charset != null && options.Charset.ToUpper() == "UTF-8");

			ArrayList ds_list = options.DataSourceList;
			if (ds_list != null)
			{
				if (ds_list.Count <= 1)
					useRoundRobin = false;

				if (ds_list.Count > 1 && useRoundRobin)
					startIndex = hostIndex = rnd.Next(ds_list.Count);

				while(true)
				{
			        	try {
			        		if (ds_list.Count == 0)
			        		{
							socket.Connect (GetEndPoint (null));
						}
						else
						{
							socket.Connect (GetEndPoint ((string)ds_list[hostIndex]));
						}
			        	        break;
			        	} catch (SocketException e) {
			        		hostIndex++;
			        		if (useRoundRobin)
			        		{
			        			if (ds_list.Count == hostIndex)
			        				hostIndex = 0;
			        			if (hostIndex == startIndex)
			        				throw e;
			        		}
			        		else if (ds_list.Count == hostIndex) // Failover mode last rec
			        		{
			        			throw e;
			        		}
			        	}
				}
			}

			try
			{
				session = new TcpSession (this, socket);
                		socket.NoDelay = true;

#if MONO
				Future future = new Future (Service.CallerId, new object[] { null });
#else
				Future future = new Future (Service.CallerId, (object) null); // not object[]
#endif
				future.SendRequest (session, options.ConnectionTimeout);
				object[] results = (object[]) future.GetResultSerial (session);
				peer = (string) results[1];

				object[] idOpts = null;
				if (results.Length > 2)
					idOpts = (object[]) results[2];
				int pwdClearCode = GetConnectionOption (idOpts, "SQL_ENCRYPTION_ON_PASSWORD", -1);
				Debug.WriteLineIf (Switch.Enabled, "pwdClearCode: " + pwdClearCode);

				string user = options.UserId;
				string password = null;
				if (pwdClearCode == 1)
					password = options.Password;
				else if (pwdClearCode == 2)
					password = MagicEncrypt (user, options.Password);
				else
					password = Digest (user, options.Password, peer);

				object[] info = new object[6];
				info[0] = ".NET Application";
				info[1] = 0;
				info[2] = Environment.MachineName;
				info[3] = ".NET";
				info[4] = options.Charset != null ? options.Charset.ToUpper () : "";
				info[5] = 0;
				future = new Future (Service.Connect, user, password, Values.VERSION, info);
				future.SendRequest (session, options.ConnectionTimeout);
				results = future.GetResultSerial (session) as object[];
				if (results == null)
					throw new SystemException ("Login failed.");
				switch ((AnswerTag) results[0])
				{
				case AnswerTag.QA_LOGIN:
					SetConnectionOptions (results);
					break;

				case AnswerTag.QA_ERROR:
					throw new SystemException (results[1].ToString () + " " + results[2].ToString ());

				default:
					throw new SystemException ("Bad login response.");
				}

				if (options.Database != null
					&& options.Database != String.Empty
					&& options.Database != currentCatalog)
					SetCurrentCatalog (options.Database);
			}
			catch (Exception)
			{
				Close ();
				throw;
			}
		}
예제 #13
0
 /// <summary>
 ///
 /// </summary>
 public void Ready()
 {
     _tcpSession = _serfClient.TcpSessionsAddOrUpdate(
         new TcpSession(_serfClient.SerfConfigurationOptions.Listening)
         .Connect(_serfClient.SerfConfigurationOptions.RPC));
 }
예제 #14
0
파일: Server.cs 프로젝트: Fantoom/TicTacToe
 protected override void OnDisconnected(TcpSession session)
 {
     // base.OnDisconnected(session);
     players.RemoveAll(x => x.PlayerId == session.Id);
 }
예제 #15
0
        public override void Open(ConnectionOptions options)
        {
            Socket socket        = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            bool   useRoundRobin = options.RoundRobin;
            int    hostIndex     = 0;
            int    startIndex    = 0;

            charset_utf8 = (options.Charset != null && options.Charset.ToUpper() == "UTF-8");

            ArrayList ds_list = options.DataSourceList;

            if (ds_list != null)
            {
                if (ds_list.Count <= 1)
                {
                    useRoundRobin = false;
                }

                if (ds_list.Count > 1 && useRoundRobin)
                {
                    startIndex = hostIndex = rnd.Next(ds_list.Count);
                }

                while (true)
                {
                    try {
                        if (ds_list.Count == 0)
                        {
                            socket.Connect(GetEndPoint(null));
                        }
                        else
                        {
                            socket.Connect(GetEndPoint((string)ds_list[hostIndex]));
                        }
                        break;
                    } catch (SocketException e) {
                        hostIndex++;
                        if (useRoundRobin)
                        {
                            if (ds_list.Count == hostIndex)
                            {
                                hostIndex = 0;
                            }
                            if (hostIndex == startIndex)
                            {
                                throw e;
                            }
                        }
                        else if (ds_list.Count == hostIndex)                         // Failover mode last rec
                        {
                            throw e;
                        }
                    }
                }
            }

            try
            {
                session        = new TcpSession(this, socket);
                socket.NoDelay = true;

#if MONO
                Future future = new Future(Service.CallerId, new object[] { null });
#else
                Future future = new Future(Service.CallerId, (object)null);                   // not object[]
#endif
                future.SendRequest(session, options.ConnectionTimeout);
                object[] results = (object[])future.GetResultSerial(session);
                peer = (string)results[1];

                object[] idOpts = null;
                if (results.Length > 2)
                {
                    idOpts = (object[])results[2];
                }
                int pwdClearCode = GetConnectionOption(idOpts, "SQL_ENCRYPTION_ON_PASSWORD", -1);
                Debug.WriteLineIf(Switch.Enabled, "pwdClearCode: " + pwdClearCode);

                string user     = options.UserId;
                string password = null;
                if (pwdClearCode == 1)
                {
                    password = options.Password;
                }
                else if (pwdClearCode == 2)
                {
                    password = MagicEncrypt(user, options.Password);
                }
                else
                {
                    password = Digest(user, options.Password, peer);
                }

                object[] info = new object[6];
                info[0] = ".NET Application";
                info[1] = 0;
                info[2] = Environment.MachineName;
                info[3] = ".NET";
                info[4] = options.Charset != null?options.Charset.ToUpper() : "";

                info[5] = 0;
                future  = new Future(Service.Connect, user, password, Values.VERSION, info);
                future.SendRequest(session, options.ConnectionTimeout);
                results = future.GetResultSerial(session) as object[];
                if (results == null)
                {
                    throw new SystemException("Login failed.");
                }
                switch ((AnswerTag)results[0])
                {
                case AnswerTag.QA_LOGIN:
                    SetConnectionOptions(results);
                    break;

                case AnswerTag.QA_ERROR:
                    throw new SystemException(results[1].ToString() + " " + results[2].ToString());

                default:
                    throw new SystemException("Bad login response.");
                }

                if (options.Database != null &&
                    options.Database != String.Empty &&
                    options.Database != currentCatalog)
                {
                    SetCurrentCatalog(options.Database);
                }
            }
            catch (Exception)
            {
                Close();
                throw;
            }
        }
예제 #16
0
파일: StunClient.cs 프로젝트: tommybiteme/X
 /// <summary>在指定套接字上执行查询</summary>
 /// <param name="socket"></param>
 /// <returns></returns>
 public StunClient(ISocket socket)
 {
     // UDP可以直接使用,而Tcp需要另外处理
     Socket = socket as ISocketClient;
     if (Socket == null)
     {
         //var client = NetService.Container.Resolve<ISocketClient>(socket.Local.ProtocolType);
         //var tcp = new TcpClient();
         //tcp.Client = socket.Client;
         Socket = new TcpSession(socket.Client);
     }
 }
예제 #17
0
        protected override void OnDisconnected(TcpSession session)
        {
            _gameServerSessionsById.Remove(session.Id);

            MulticastNullTerminated($"PLAYERLEFT:{session.Id}");
        }
예제 #18
0
 public AuthPacketRouter(TcpSession session, IGrainFactory grainFactory) : base(session)
 {
     GrainFactory = grainFactory;
     AuthSession  = GrainFactory.GetGrain <IAuthSession>(Session.Id);
     packetReader = new AuthPacketReader();
 }
예제 #19
0
        private void HandshakeConnection(string Type, IPEndPoint ip, string username, string password, TcpSession session, Packet ack)
        {
            switch (Type)
            {
            // Success
            case "success":
                var newSession = _sessions.AddSession(AuthDatabase.Instance.GetAccountID(username), ip.Address);
                _logger.Info("Succesfully authenticated Username: {0} with SessionID: {1}", username, newSession.SessionID);

                ack.Write(newSession.SessionID); // session id
                ack.Write(new byte[12]);         // unk
                ack.Write((byte)ELoginResult.OK);
                session.Send(ack);
                break;

            // Invalid password/username combination
            case "failed":
                _logger.Error("Failed login for Username: {0}", username);
                ack.Write((uint)0);
                ack.Write(new byte[12]);
                ack.Write((byte)ELoginResult.AccountError);
                session.Send(ack);
                session.StopListening();
                break;

            // Banned account tried to login
            case "banned":
                _logger.Error("Failed login for Username: {0}", username);
                ack.Write((uint)0);
                ack.Write(new byte[12]);
                ack.Write((byte)ELoginResult.AccountBlocked);
                session.Send(ack);
                session.StopListening();
                break;

            default:
                break;
            }
        }
예제 #20
0
 protected override void OnDisconnected(TcpSession session)
 {
     Disconnected = true; Clients--;
 }
예제 #21
0
파일: P2PClient.cs 프로젝트: tommybiteme/X
        void EnsureClient()
        {
            EnsureServer();
            if (Client == null)
            {
                var server = Server;

                var client = new TcpSession();
                Client = client;
                //client.Address = server.LocalEndPoint.Address;
                //client.Port = server.LocalEndPoint.Port;
                //client.ReuseAddress = true;
                //client.Connect(HoleServer);
                //var session = client.CreateSession();
                var session = client as ISocketSession;
                session.Received += client_Received;
                client.ReceiveAsync();
            }
        }
예제 #22
0
 public ClientConnectedEventArgs(TcpSession session)
 {
     Session = session;
 }
예제 #23
0
파일: P2PClient.cs 프로젝트: tommybiteme/X
        void client_Received(object sender, ReceivedEventArgs e)
        {
            //WriteLog("数据到来:{0} {1}", e.RemoteIPEndPoint, e.GetString());

            //var ss = e.GetString().Split(":");
            var ss = e.Stream.ToStr().Split(":");
            if (ss == null || ss.Length < 2) return;

            IPAddress address = null;
            if (!IPAddress.TryParse(ss[0], out address)) return;
            Int32 port = 0;
            if (!Int32.TryParse(ss[1], out port)) return;
            var ep = new IPEndPoint(address, port);
            ParterAddress = ep;

            Client.Dispose();
            var server = Server;

            //Random rnd = new Random((Int32)DateTime.Now.Ticks);
            Thread.Sleep(Rand.Next(0, 2000));

            var client = new TcpSession();
            Client = client;
            //client.Address = server.LocalEndPoint.Address;
            //client.Port = server.LocalEndPoint.Port;
            //client.ReuseAddress = true;
            client.Local.EndPoint = server.Local.EndPoint;
            Console.WriteLine("准备连接对方:{0}", ep);
            try
            {
                //client.Connect(ep);
                client.Received += client_Received2;
                client.ReceiveAsync();

                Client.Send("Hello!");
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message);
            }
        }
예제 #24
0
 protected override void OnConnected(TcpSession session)
 {
     _logger.Error($"[INTERNAL] Connection established with client GUID #{ session.Id }.");
     base.OnConnected(session);
 }
예제 #25
0
파일: P2PClient.cs 프로젝트: tommybiteme/X
        void SendToHole(String msg)
        {
            var ep = new IPEndPoint(HoleServer.Address, HoleServer.Port + 1);
            EnsureServer();
            var server = Server as UdpServer;
            if (server != null)
            {
                server.Client.Send(msg, null, HoleServer);
                //server.Send("test", null, HoleServer);
                if (msg.StartsWith("reg"))
                {
                    server.Client.Send("checknat", null, ep);
                }
            }
            else
            {
                var client = new TcpSession() as ISocketSession;
                //client.Address = Server.LocalEndPoint.Address;
                //client.Port = Server.LocalEndPoint.Port;
                //client.ReuseAddress = true;
                //client.Connect(ep);
                client.Local.EndPoint = Server.Local.EndPoint;
                client.Send("checknat");
                WriteLog("HoleServer数据到来:{0}", client.ReceiveString());
                client.Dispose();

                EnsureClient();
                //Client.Send(msg, null);
                Client.Send(msg);
            }
        }
예제 #26
0
        void Connect()
        {
            _Server = null;
            _Client = null;

            var port = (Int32)numPort.Value;

            var cfg = NetConfig.Current;

            cfg.Port = port;

            var mode = GetMode();

            switch (mode)
            {
            case WorkModes.UDP_TCP:
                _Server = new NetServer();
                break;

            case WorkModes.UDP_Server:
                _Server = new NetServer();
                _Server.ProtocolType = NetType.Udp;
                break;

            case WorkModes.TCP_Server:
                _Server = new NetServer();
                _Server.ProtocolType = NetType.Tcp;
                break;

            case WorkModes.TCP_Client:
                var tcp = new TcpSession();
                _Client = tcp;

                cfg.Address = cbAddr.Text;
                break;

            case WorkModes.UDP_Client:
                var udp = new UdpServer();
                _Client = udp;

                cfg.Address = cbAddr.Text;
                break;

            default:
                if ((Int32)mode > 0)
                {
                    var ns = GetNetServers().Where(n => n.Name == cbMode.Text).FirstOrDefault();
                    if (ns == null)
                    {
                        throw new XException("未识别服务[{0}]", mode);
                    }

                    _Server = ns.GetType().CreateInstance() as NetServer;
                }
                break;
            }

            if (_Client != null)
            {
                _Client.Log         = cfg.ShowLog ? XTrace.Log : Logger.Null;
                _Client.Received   += OnReceived;
                _Client.Remote.Port = port;
                _Client.Remote.Host = cbAddr.Text;

                _Client.LogSend    = cfg.ShowSend;
                _Client.LogReceive = cfg.ShowReceive;

                _Client.Open();

                "已连接服务器".SpeechTip();
            }
            else if (_Server != null)
            {
                if (_Server == null)
                {
                    _Server = new NetServer();
                }
                _Server.Log       = cfg.ShowLog ? XTrace.Log : Logger.Null;
                _Server.SocketLog = cfg.ShowSocketLog ? XTrace.Log : Logger.Null;
                _Server.Port      = port;
                if (!cbAddr.Text.Contains("所有本地"))
                {
                    _Server.Local.Host = cbAddr.Text;
                }
                _Server.Received += OnReceived;

                _Server.LogSend    = cfg.ShowSend;
                _Server.LogReceive = cfg.ShowReceive;

                _Server.Start();

                "正在监听{0}".F(port).SpeechTip();
            }

            pnlSetting.Enabled = false;
            btnConnect.Text    = "关闭";

            cfg.Save();

            _timer = new TimerX(ShowStat, null, 5000, 5000);

            BizLog = TextFileLog.Create("NetLog");
        }
예제 #27
0
        /// <summary>
        /// 反序列化接收到的数据,输出message
        /// messageHandler需要保证线程安全
        /// </summary>
        public TcpSession.ReceivedHandler CreateReceivedHandler(TcpSession session, Action <TcpSession, object> messageHandler)
        {
            bool isInitialized   = false;
            bool isReadingHeader = true;
            bool isPartial       = false;
            var  partialStream   = new MemoryStream();

            TcpSession.ReceivedHandler handler = stream =>
            {
                if (!isInitialized)
                {
                    Debug.Assert(stream.Length == 0 && stream.Position == 0);
                    isInitialized = true;
                    return(PackageHead.SizeOf);
                }
                if (isReadingHeader)
                {
                    PackageHead header = new PackageHead();
                    header.ReadFrom(stream.GetBuffer(), (int)stream.Position);
                    isReadingHeader = false;
                    isPartial       = ((header.Flags & PackageHeadFlags.Partial) == PackageHeadFlags.Partial);
                    return(header.MessageLength);
                }
                else
                {
                    if (isPartial) // 超大包未接收完全
                    {
                        // 在临时缓冲中拼包
                        stream.WriteTo(partialStream);
                    }
                    else if (partialStream.Length != 0) // 超大包最后一个分包
                    {
                        // 拼包然后反序列化
                        stream.WriteTo(partialStream);
                        object message = null;
                        try
                        {
                            message = this.serializer.Deserialize(partialStream.GetBuffer(), 0, (int)partialStream.Length);
                        }
                        catch (Exception e)
                        {
                            OnMessageDeserializeFailed(e);
                        }

                        if (message != null)
                        {
                            messageHandler(session, message);
                        }

                        partialStream.Position = 0;
                        partialStream.SetLength(0);
                    }
                    else // 普通大小的包
                    {
                        // 直接反序列化
                        object message = null;
                        try
                        {
                            message = this.serializer.Deserialize(stream.GetBuffer(), (int)stream.Position, (int)stream.Length);
                        }
                        catch (Exception e)
                        {
                            OnMessageDeserializeFailed(e);
                        }

                        if (message != null)
                        {
                            messageHandler(session, message);
                        }
                    }

                    isReadingHeader = true;
                    return(PackageHead.SizeOf);
                }
            };

            return(handler);
        }
예제 #28
0
 public PacketReceivedEventArgs(TcpSession session, byte[] data)
 {
     Session = session;
     Packet = new Packet(data);
 }
 protected abstract void Handle_RequestEcho(TcpSession sender, string message);
예제 #30
0
 public ClientDisconnectedEventArgs(TcpSession session)
 {
     Session = session;
 }
예제 #31
0
        /// <summary>
        /// 反序列化接收到的数据,输出message 
        /// messageHandler需要保证线程安全
        /// </summary>
        public TcpSession.ReceivedHandler CreateReceivedHandler(TcpSession session, Action<TcpSession, object> messageHandler)
        {
            bool isInitialized = false;
            bool isReadingHeader = true;
            bool isPartial = false;
            var partialStream = new MemoryStream();
            TcpSession.ReceivedHandler handler = stream =>
            {
                if (!isInitialized)
                {
                    Debug.Assert(stream.Length == 0 && stream.Position == 0);
                    isInitialized = true;
                    return PackageHead.SizeOf;
                }
                if (isReadingHeader)
                {
                    PackageHead header = new PackageHead();
                    header.ReadFrom(stream.GetBuffer(), (int)stream.Position);
                    isReadingHeader = false;
                    isPartial = ((header.Flags & PackageHeadFlags.Partial) == PackageHeadFlags.Partial);
                    return header.MessageLength;
                }
                else
                {
                    if (isPartial) // 超大包未接收完全
                    {
                        // 在临时缓冲中拼包
                        stream.WriteTo(partialStream);
                    }
                    else if (partialStream.Length != 0) // 超大包最后一个分包
                    {
                        // 拼包然后反序列化
                        stream.WriteTo(partialStream);
                        object message = null;
                        try
                        {
                           message = this.serializer.Deserialize(partialStream.GetBuffer(), 0, (int)partialStream.Length);
                        }
                        catch (Exception e)
                        {
                            OnMessageDeserializeFailed(e);
                        }

                        if (message != null)
                            messageHandler(session, message);

                        partialStream.Position = 0;
                        partialStream.SetLength(0);
                    }
                    else // 普通大小的包
                    {
                        // 直接反序列化
                        object message = null;
                        try
                        {
                            message = this.serializer.Deserialize(stream.GetBuffer(), (int)stream.Position, (int)stream.Length);
                        }
                        catch (Exception e)
                        {
                            OnMessageDeserializeFailed(e);
                        }

                        if (message != null)
                            messageHandler(session, message);
                    }

                    isReadingHeader = true;
                    return PackageHead.SizeOf;
                }
            };

            return handler;
        }
예제 #32
0
        private void HandleBRSFriendNotify(TcpSession session, Packet p)
        {
            var accID    = p.ReadUInt64();
            var accepted = p.ReadInt32() > 0;
            var nickname = p.ReadCStringBuffer(31);
            //_logger.Debug("-C_ADD_FRIEND_REQ- ID: {0} Nickname: {1}", accID, nickname);

            Player plr;

            if (!_players.TryGetValue(session.Guid, out plr))
            {
                session.StopListening();
                return;
            }
            Packet ack;

            var plrFromRequest = _players.GetPlayerByID(accID);

            if (plrFromRequest == null)
            {
                return;
            }

            if (accepted)
            {
                SendBRSFriendNotify(plr, plrFromRequest, EFriendNotify.Accepted);
                SendBRSFriendNotify(plrFromRequest, plr, EFriendNotify.Accepted);
            }
            else
            {
                SendBRSFriendNotify(plr, plrFromRequest, EFriendNotify.Denied);
                SendBRSFriendNotify(plr, plrFromRequest, EFriendNotify.DeleteRelation);

                SendBRSFriendNotify(plrFromRequest, plr, EFriendNotify.DeleteRelation);
            }


            var friend = plrFromRequest.FriendList.FirstOrDefault(f => f.ID == plr.AccountID);

            if (friend == null)
            {
                return;
            }
            if (accepted)
            {
                friend.Accepted = true;
                GameDatabase.Instance.UpdateFriend(plrFromRequest.AccountID, friend.ID, friend.Accepted);

                var newFriend = new Friend()
                {
                    ID       = plrFromRequest.AccountID,
                    Nickname = plrFromRequest.Nickname,
                    Accepted = true
                };
                plr.FriendList.Add(newFriend);
                GameDatabase.Instance.AddFriend(plr.AccountID, newFriend.ID, newFriend.Nickname, newFriend.Accepted);
            }
            else
            {
                plrFromRequest.FriendList.Remove(friend);
                GameDatabase.Instance.RemoveFriend(plrFromRequest.AccountID, friend.ID);
            }
        }
예제 #33
0
 public virtual bool OnPacket(TcpSession session, Packet packet)
 {
     return(false);
 }
예제 #34
0
        /// <summary>
        /// Send a presence error
        /// </summary>
        /// <param name="stream">The stream that will receive the error</param>
        /// <param name="code">The error code</param>
        /// <param name="error">A string containing the error</param>
        public static void SendGPError(TcpSession session, object errorCode, string error)
        {
            string sendingBuffer = string.Format(@"\error\\err\{0}\fatal\\errmsg\{1}\id\1\final\", (uint)errorCode, error);

            session.SendAsync(sendingBuffer);
        }
예제 #35
0
        private void OnMessageMarketUnregisterRes(TcpSession session, GameMessage message)
        {
            string order = message.Get <string>("order");

            BConsole.WriteLine("market unregistered! order=", order);
        }
예제 #36
0
 protected override void OnConnected(TcpSession session)
 {
     Connected = true; Clients++;
 }
예제 #37
0
 private void OnMessageInfoRes(TcpSession session, GameMessage message)
 {
     // info
     BConsole.WriteLine(message.Get <JObject>("info"));
 }
		public override void Close ()
		{
			if (session != null)
			{
				session.Close ();
				session = null;
			}
			base.Close ();
		}
예제 #39
0
 private void OnMessageTokenRes(TcpSession session, GameMessage message)
 {
     poaToken = message.Get <string>("accessToken");
 }
예제 #40
0
 protected override void OnDisconnected(TcpSession session)
 {
     RemoveSessionOfSessionList((ChatSession)session);
     base.OnDisconnected(session);
 }
예제 #41
0
 protected override void OnDisconnected(TcpSession session)
 {
     Disconnected = true; Clients = Math.Max(Clients - 1, 0);
 }
예제 #42
0
 public abstract bool HandlePacket(TcpSession session, Packet packet);
예제 #43
0
 public PacketReceivedEventArgs(TcpSession session, byte[] data)
 {
     Session = session;
     Packet  = new Packet(data);
 }
예제 #44
0
 private void ConnectCallback(object sender, SocketAsyncEventArgs args)
 {
     try
     {
         Session = sessionCreator();
         Session.SetSocket(args.AcceptSocket);
     }
     catch (Exception e)
     {
         if (ExceptionHandler != null)
             ExceptionHandler(e);
     }
 }
예제 #45
0
        private void OnMessagePing(TcpSession session, GameMessage ping)
        {
            long timestamp = ping.Value <long>("timestamp");

            Send(new GameMessage("pong").With("timestamp", timestamp));
        }