예제 #1
0
 public GameSocketPair(DuplexStream serverStream, DuplexStream clientStream, GameSocket clientSocket, GameSocket serverSocket)
 {
     ClientStream = clientStream;
     ServerStream = serverStream;
     ClientSocket = clientSocket;
     ServerSocket = serverSocket;
 }
예제 #2
0
        public FieldUser(GameSocket socket)
        {
            Socket = socket;

            Controlled = new List <IFieldControlledObj>();
            Owned      = new List <IFieldOwnedObj>();
            Pets       = Character.Pets
                         .Where(sn => sn > 0)
                         .Select(sn => Character
                                 .Inventories[ItemInventoryType.Cash].Items.Values
                                 .OfType <ItemSlotPet>()
                                 .FirstOrDefault(i => i.CashItemSN == sn))
                         .Where(item => item != null)
                         .Select(item => new FieldUserPet(
                                     this,
                                     item,
                                     (byte)Character.Pets.IndexOf(item.CashItemSN ?? 0)
                                     ))
                         .ToList();

            BasicStat      = new BasicStat(this);
            ForcedStat     = new ForcedStat(this);
            TemporaryStats = new Dictionary <TemporaryStatType, TemporaryStat>();
            ValidateStat();
        }
예제 #3
0
 void Update()
 {
     if ((Input.GetKeyDown(KeyCode.Escape)))
     {
         OnLeave();
     }
     if (Global.GameTryReConnTimes > GameSocket.MAXRETRYTTIMES)         //重试
     {
         Global.GameTryReConnTimes = 0;
         UI_Alert.ShowMsg("连接游戏服务器超时,是否重试?", () => {
             GameSocket.GetInstance().ManualShutDown();
             GameSocket.GetInstance().Connect();
         }, () => {
             Leave();
         });
     }
     EventMgr.ins.DispEvent(EventMgr.EnterFrame, null);
     if (Global.LastGameHeartBeatTime != 0 && Global.IsLoginGame)
     {
         ulong nowTime = TimeHelper.GetNowTime();
         ulong left    = nowTime - Global.LastGameHeartBeatTime;
         if (left > 15)                            //回包超时跳出提示,重新登录
         {
             if (Global.CurrentGameId == 10301800) //重连
             {
                 GameSocket.GetInstance().ManualShutDown();
                 GameSocket.GetInstance().Connect(Global.CurrentSelGameRoom.GetSzServiceIP(), (int)Global.CurrentSelGameRoom.uServicePort);
                 Global.LastGameHeartBeatTime = 0;
             }
         }
     }
 }
예제 #4
0
 void Start()
 {
     ws = new GameSocket <MessagePackPacker>("ws://localhost:8080/");
     // ws.RegistOnServerPush((_sender, _packet) => {
     //     Debug.Log("Server Pushed");
     // });
 }
예제 #5
0
        private static void RegisterLoginHandlers(object source, EventArgs args)
        {
            GameSocket socket = (GameSocket)source;

            socket.PacketHandlers[206, GameSocketMessageHandlerPriority.DefaultAction]  += PacketHandlers.ProcessEncryptionRequest;
            socket.PacketHandlers[2002, GameSocketMessageHandlerPriority.DefaultAction] += PacketHandlers.ProcessSessionRequest;
            socket.PacketHandlers[204, GameSocketMessageHandlerPriority.DefaultAction]  += PacketHandlers.ProcessSSOTicket;
        }
예제 #6
0
 public static GameSocket GetInstance()
 {
     if (instance == null)
     {
         instance = new GameSocket();
     }
     return(instance);
 }
예제 #7
0
 public TestLauncher(GameSocketStressTest owner, NetworkStream server, NetworkStream client)
 {
     this.owner  = owner;
     this.server = new GameSocket();
     this.server.registerRequestReceiver(new DummyRequestReceiver());
     this.server.AttachNetworkStream(server);
     this.client = new GameSocket();
     this.client.AttachNetworkStream(client);
 }
예제 #8
0
        public async Task SendPacketAsync(GameSocket socket, int id, byte[] authToken, FinishListener finishAction)
        {
            var message = new MemoryStream();
            await message.WriteAsync(id);

            await message.WriteByteArrayAsync(authToken);

            await socket.SendRequestAsync(Key, message, (int)message.Length, new LoginAccountReceiver(socket, finishAction));
        }
예제 #9
0
파일: UserBase.cs 프로젝트: octgn/OCTGN4
 protected UserBase(GameServer server, GameSocket sock)
 {
     Username       = "";
     Server         = server;
     _socket        = sock;
     Connected      = true;
     RPCInterceptor = new RpcInterceptor(_socket);
     RPC            = _generator.CreateInterfaceProxyWithoutTarget <IS2CComs>(RPCInterceptor);
     Id             = System.Threading.Interlocked.Increment(ref _lastId);
 }
예제 #10
0
파일: UserBase.cs 프로젝트: octgn/OCTGN4
 protected UserBase(UserBase user)
 {
     _socket        = user._socket;
     Server         = user.Server;
     Connected      = user.Connected;
     RPC            = user.RPC;
     Id             = user.Id;
     user.Replaced  = this;
     RPCInterceptor = user.RPCInterceptor;
     Username       = user.Username.Clone() as string;
 }
예제 #11
0
 void OnApplicationPause(bool Pause)
 {
     if (Pause)
     {
         Global.LastGameHeartBeatTime = 0;            //防止网络检查与此处冲突
         GameSocket.GetInstance().Pause();
     }
     else
     {
         GameSocket.GetInstance().Resume();
     }
 }
예제 #12
0
        public static GameSocketPair Create()
        {
            // Create streams
            var serverStream = new DuplexStream();
            var clientStream = serverStream.CreateReverseDuplexStream();

            return(new GameSocketPair(
                       serverStream,
                       clientStream,
                       clientSocket: GameSocket.CreateFromStream(clientStream, isServer: false, subProtocol: null, keepAliveInterval: TimeSpan.FromMinutes(2)),
                       serverSocket: GameSocket.CreateFromStream(serverStream, isServer: true, subProtocol: null, keepAliveInterval: TimeSpan.FromMinutes(2))));
        }
예제 #13
0
 public static void RegisterLogin(GameSocket socket, Account account)
 {
     foreach (KeyValuePair <GameSocket, Account> connection in Connections)
     {
         if (connection.Value.Id == account.Id)
         {
             Connections.Remove(connection.Key);
             break;
         }
     }
     Connections[socket] = account;
 }
예제 #14
0
        private async Task Echo(GameSocket gameSocket, CancellationToken cancellationToken)
        {
            var buffer = new byte[1024 * 4];
            var result = await gameSocket.ReceiveAsync(new ArraySegment <byte>(buffer), cancellationToken);

            while (!result.CloseStatus.HasValue)
            {
                await gameSocket.SendAsync(new ArraySegment <byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, cancellationToken);

                result = await gameSocket.ReceiveAsync(new ArraySegment <byte>(buffer), cancellationToken);
            }
            await gameSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, cancellationToken);
        }
예제 #15
0
        public static void RegisterReceivers(GameSocket socket)
        {
            #region Login
            socket.registerRequestReceiver(new HandshakeReceiver(socket));
            socket.registerRequestReceiver(new LoginAccountReceiver(socket));
            socket.registerRequestReceiver(new GenerateAccountReceiver());
            socket.registerRequestReceiver(new FetchDataReceiver(socket));
            #endregion

            #region Resource
            socket.registerRequestReceiver(new GetResourceStatusReceiver(socket));
            #endregion
        }
예제 #16
0
        protected void InitSocket()
        {
            m_socket = new GameSocket();

            m_socket.ConnectedSuccess += new ConnectSocketDelegate(m_socket_ConnectedSuccess);
            m_socket.ConnectedFaild   += new ConnectSocketDelegate(m_socket_ConnectedFaild);

            m_socket.AcceptedSocket += new AcceptSocketDelegate(m_socket_AcceptedSocket);

            m_socket.Received += new ReceivePacketDelegate(m_socket_Received);

            m_socket.Disconnected += new DisconnectSocketDelegate(m_socket_Disconnected);
        }
예제 #17
0
 public GameClient(string host, User user)
 {
     Id               = Interlocked.Increment(ref _nextId);
     _host            = host;
     User             = user;
     _cancellation    = new CancellationTokenSource();
     _socket          = new GameSocket(host);
     Port             = _socket.Endpoint.Port;
     _state           = new GameState(this);
     RPC              = _generator.CreateInterfaceProxyWithoutTarget <IC2SComs>(new RpcInterceptor(_socket));
     ResourceResolver = new ResourceResolver(this);
     UIRPC            = new GameUIRPC();
 }
예제 #18
0
 static int CloseWeb(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 1);
         GameSocket obj = (GameSocket)ToLua.CheckObject <GameSocket>(L, 1);
         obj.CloseWeb();
         return(0);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
예제 #19
0
        internal GameSocketAdapter(GameSocket gameSocket, CancellationToken ct)
        {
            _gameSocket        = gameSocket;
            _cancellationToken = ct;

            _environment = new Dictionary <string, object>();
            _environment[OwinConstants.GameSocket.SendAsync]     = new GameSocketSendAsync(SendAsync);
            _environment[OwinConstants.GameSocket.ReceiveAsync]  = new GameSocketReceiveAsync(ReceiveAsync);
            _environment[OwinConstants.GameSocket.CloseAsync]    = new GameSocketCloseAsync(CloseAsync);
            _environment[OwinConstants.GameSocket.CallCancelled] = ct;
            _environment[OwinConstants.GameSocket.Version]       = OwinConstants.GameSocket.VersionValue;

            _environment[typeof(GameSocket).FullName] = gameSocket;
        }
예제 #20
0
 static int GetGameWebSocketManager(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 0);
         GameSocket o = LuaFramework.LuaHelper.GetGameWebSocketManager();
         ToLua.Push(L, o);
         return(1);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
예제 #21
0
 static int SendMsg(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 2);
         GameSocket obj  = (GameSocket)ToLua.CheckObject <GameSocket>(L, 1);
         string     arg0 = ToLua.CheckString(L, 2);
         obj.SendMsg(arg0);
         return(0);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
예제 #22
0
        public GameSocket AcceptClient(WebSocket websocket)
        {
            GameSocket socket = new GameSocket(websocket);

            lock (connectedPlayers)
            {
                connectedPlayers.Add(socket);
            }

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("A challenger #" + connectedPlayers.Count + " arrived!");
            Console.ForegroundColor = ConsoleColor.White;

            return(socket);
        }
예제 #23
0
 public static Account GetLogin(GameSocket socket, bool autoException = true)
 {
     if (Connections.ContainsKey(socket))
     {
         return(Connections[socket]);
     }
     else
     {
         if (autoException)
         {
             throw new Exception("세션이 만료되었습니다");
         }
         return(null);
     }
 }
예제 #24
0
            async Task <GameSocket> IProtoGameSocketFeature.AcceptAsync(GameSocketAcceptContext context)
            {
                var gamesockets = TestGameSocket.CreatePair(context.SubProtocol);

                if (_httpContext.Response.HasStarted)
                {
                    throw new InvalidOperationException("The response has already started");
                }

                _httpContext.Response.StatusCode = StatusCodes.Status101SwitchingProtocols;
                ClientGameSocket = gamesockets.Item1;
                ServerGameSocket = gamesockets.Item2;
                await _httpContext.Response.Body.FlushAsync(_httpContext.RequestAborted); // Send headers to the client

                return(ServerGameSocket);
            }
 IEnumerator StartConnect(System.Action callback = null)
 {
     socket = new GameSocket(host, port);
     socket.onReceiveMessage = this.OnReceiveMsg;
     socket.onDisconnect     = this.OnDisconnected;
     socket.onConnected      = this.OnConnected;
     socket.Connect();
     while (!socket.Connected)
     {
         yield return(null);
     }
     if (callback != null)
     {
         callback();
     }
     StartCoroutine(socket.Dispatcher());
 }
예제 #26
0
    static int set_webSocket(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            GameSocket obj = (GameSocket)o;
            BestHTTP.WebSocket.WebSocket arg0 = (BestHTTP.WebSocket.WebSocket)ToLua.CheckObject(L, 2, typeof(BestHTTP.WebSocket.WebSocket));
            obj.webSocket = arg0;
            return(0);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o, "attempt to index webSocket on a nil value"));
        }
    }
예제 #27
0
    void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
        }

        if (Instance != this)
        {
            Destroy(gameObject);
        }

        DontDestroyOnLoad(gameObject);


        m_gameSocket = new GameSocket(OnConnected, OnDisconnect, OnMessage);
    }
예제 #28
0
    static int get_webSocket(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            GameSocket obj = (GameSocket)o;
            BestHTTP.WebSocket.WebSocket ret = obj.webSocket;
            ToLua.PushSealed(L, ret);
            return(1);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o, "attempt to index webSocket on a nil value"));
        }
    }
예제 #29
0
    static int set_MIsSendHeatBeat(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            GameSocket obj  = (GameSocket)o;
            bool       arg0 = LuaDLL.luaL_checkboolean(L, 2);
            obj.MIsSendHeatBeat = arg0;
            return(0);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o, "attempt to index MIsSendHeatBeat on a nil value"));
        }
    }
예제 #30
0
 //Listener
 public static async Task StartServerSocketAsync()
 {
     _cancellationServerToken = CancellationTokenSource.CreateLinkedTokenSource(new CancellationToken());
     while (!_cancellationServerToken.Token.IsCancellationRequested)
     {
         await Task.Run(async() =>
         {
             TcpClient client = await GameSocket.AcceptTcpClientAsync();
             client.NoDelay   = true;
             ProtocolModel.ConnectionClient connectionClient = new ProtocolModel.ConnectionClient
             {
                 Id     = Guid.NewGuid().ToString(),
                 Client = client
             };
             Clients.Add(connectionClient);
             ReadFromClient(connectionClient);
         }, _cancellationServerToken.Token);
     }
 }
예제 #31
0
        protected void InitSocket()
        {
            m_socket = new GameSocket();

            m_socket.ConnectedSuccess += new ConnectSocketDelegate(m_socket_ConnectedSuccess);
            m_socket.ConnectedFaild += new ConnectSocketDelegate(m_socket_ConnectedFaild);

            m_socket.AcceptedSocket += new AcceptSocketDelegate(m_socket_AcceptedSocket);

            m_socket.Received += new ReceivePacketDelegate(m_socket_Received);

            m_socket.Disconnected += new DisconnectSocketDelegate(m_socket_Disconnected);
        }
예제 #32
0
        public override void AfterInvoke(InvocationInfo info, ref object returnValue)
        {
            if( activeTrade != null && info.targetMethod.Equals("updateGraphics") ) {
                activeTrade.PostOverlayRender((Card)info.arguments[0]);
            } else if( activeTrade != null && info.targetMethod.Equals("UpdateView") ) {
                activeTrade.PostUpdateView();
            } else if( info.targetMethod.Equals("OnGUI") && info.target.GetType() == deckType ) {
                deckManager.OnGUI(info.target as DeckBuilder2);
            }

            if(info.target is GameSocket && info.targetMethod.Equals("Init"))
            {
                Console.WriteLine("gamesocket init");
                this.gs = (GameSocket)info.target;
            }

            return;
        }
예제 #33
0
 public void setgs(GameSocket gees)
 {
     Console.WriteLine("setgs");
     this.gs=gees;
 }
예제 #34
0
        public ReplayRunner(ScrollsPost.Mod mod, String path, GameSocket gs)
        {
            this.mod = mod;
            this.gs = gs;
            // Convert a .sgr replay to .spr
            if( path.EndsWith(".sgr") ) {
                path = ConvertScrollsGuide(path);
            }

            this.replayPrimaryPath = path;
            this.primaryType = path.EndsWith("-white.spr") ? "white" : "black";

            // Check if we have both perspectives available to us
            String secondary = path.EndsWith("-white.spr") ? path.Replace("-white.spr", "-black.spr") : path.Replace("-black.spr", "-white.spr");
            if( File.Exists(secondary) ) {
                this.replaySecondaryPath = secondary;
            } else if( !secondary.Contains(mod.replayLogger.replayFolder) ) {
                // In case we're playing a replay from the download folder but we have the primary in our replay folder
                secondary = mod.replayLogger.replayFolder + Path.DirectorySeparatorChar + Path.GetFileName(secondary);
                if( File.Exists(secondary) ) {
                    this.replaySecondaryPath = secondary;
                }
            }

            // Always make sure the white is the primary as that person starts off the game
            if( !String.IsNullOrEmpty(this.replaySecondaryPath) && this.primaryType.Equals("black") ) {
                path = this.replayPrimaryPath;
                this.replayPrimaryPath = this.replaySecondaryPath;
                this.replaySecondaryPath = path;
                this.primaryType = "white";
            }

            GUISkin skin = (GUISkin)Resources.Load("_GUISkins/LobbyMenu");
            this.buttonStyle = skin.button;
            this.buttonStyle.normal.background = this.buttonStyle.hover.background;
            this.buttonStyle.normal.textColor = new Color(1f, 1f, 1f, 1f);
            this.buttonStyle.fontSize = (int)((10 + Screen.height / 72) * 0.65f);

            this.buttonStyle.hover.textColor = new Color(0.80f, 0.80f, 0.80f, 1f);

            this.buttonStyle.active.background = this.buttonStyle.hover.background;
            this.buttonStyle.active.textColor = new Color(0.60f, 0.60f, 0.60f, 1f);

            this.speedButtonStyle = new GUIStyle(this.buttonStyle);
            this.speedButtonStyle.fontSize = (int)Math.Round(this.buttonStyle.fontSize * 0.80f);

            this.realTimeButtonStyle = new GUIStyle(this.buttonStyle);
            this.realTimeButtonStyle.fontSize = (int)Math.Round(this.buttonStyle.fontSize * 1.20f);

            sceneLoaded = false;

            deselectMethod = typeof(BattleMode).GetMethod("deselectAllTiles", BindingFlags.Instance | BindingFlags.NonPublic);
            effectField = typeof(BattleMode).GetField("currentEffect", BindingFlags.NonPublic | BindingFlags.Instance);
            animFrameField = typeof(AnimPlayer).GetField("_fframe", BindingFlags.NonPublic | BindingFlags.Instance);
            nextMessageMethod = typeof(MiniCommunicator).GetMethod("_handleMessage", BindingFlags.NonPublic | BindingFlags.Instance);
            //tmpUpdate = typeof(ThreadedMessageParser).GetMethod("update", BindingFlags.NonPublic | BindingFlags.Instance);
            dispatchMessages = typeof(MiniCommunicator).GetMethod("_dispatchMessageToListeners", BindingFlags.NonPublic | BindingFlags.Instance);
            Console.WriteLine("start replay");

            playerThread = new Thread(new ThreadStart(Start));
            playerThread.Start();
        }
예제 #35
0
        public virtual void Accept(Socket socket, byte[] sBuff, byte[] rBuff)
        {
            if (m_socket != null || socket == null) return;

            if (sBuff == null) sBuff = new byte[BuffSize];
            if (rBuff == null) rBuff = new byte[BuffSize];

            m_socket = new GameSocket(sBuff, rBuff);
            m_socket.Accept(socket);

            m_socket.Received += new ReceivePacketDelegate(m_socket_Received);
            m_socket.Disconnected += new DisconnectSocketDelegate(m_socket_Disconnected);
        }
예제 #36
0
파일: Game1.cs 프로젝트: HY-Space/HY-Tank
        public Game1(int size,IPAddress serverIP, int serverPort, IPAddress clientIP, int clientPort)
        {
            columnsGrid = rowsGrid = size;
            p0 = new PlayerInfo(-1, -1);
            p1 = new PlayerInfo(-1, -1);
            p2 = new PlayerInfo(-1, -1);
            p3 = new PlayerInfo(-1, -1);
            p4 = new PlayerInfo(-1, -1);
            gs = new GameSocket(serverIP, serverPort, clientIP, clientPort);
            game = this;
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            arena = new char[columnsGrid, columnsGrid];
            tankGrid = new int[columnsGrid, columnsGrid];
            cellWidth = gridSizeInPixels / columnsGrid;
            cellHeight = gridSizeInPixels / rowsGrid;
            //arena[0, 1] = 's'; arena[9, 0] = 's'; arena[9, 1] = 's'; arena[9, 2] = 's'; arena[8, 1] = 's'; arena[8, 0] = 's'; arena[5, 0] = 'w'; arena[5, 1] = 'w'; arena[4, 0] = 'w'; arena[4, 1] = 'w'; arena[6, 9] = 'b'; arena[6, 8] = 'b'; arena[5, 9] = 'b'; arena[5, 8] = 'b';

            players[0] = p0; players[1] = p1; players[2] = p2; players[3] = p3; players[4] = p4;

            for (int i = 0; i < tankGrid.GetLength(0); i++)//initializing tankgrid for all -1s
            {
                for (int j = 0; j < tankGrid.GetLength(0); j++)
                {
                    tankGrid[i, j] = -1;
                }
            }

            gs.setGrid(arena, p0, p1, p2, p3, p4, gridSizeInPixels, columnsGrid);

            tankCentre = new Vector2(49, 49);//origin needs to be defined with respect to the original image
            tankScale = cellWidth * 1f / 100;
            bulletCentre = new Vector2(500, 500);//origin needs to be defined with respect to the original image
            bulletScale = cellWidth * 1f / 1000;
            playerCentre = new Vector2(50, 50);//origin needs to be defined with respect to the original image
            coinsCentre = new Vector2(50, 50);
            lifepackCentre = new Vector2(50, 50);
            coinsScale = lifepackScale = cellWidth * 1f / 100;

            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            bulletTimer.Elapsed += new ElapsedEventHandler(bulletTimer_Elapsed);
        }