コード例 #1
0
        protected override void Awake()
        {
            base.Awake();

            // Create room client connection
            roomServerConnection = Mst.Create.ClientSocket();

            // Listen toconnection statuses
            roomServerConnection.AddConnectionListener(OnClientConnectedToRoomServer, false);
            roomServerConnection.AddDisconnectionListener(OnClientDisconnectedFromRoomServer, false);

            // If master IP is provided via cmd arguments
            if (Mst.Args.IsProvided(Mst.Args.Names.MasterIp))
            {
                masterIp = Mst.Args.MasterIp;
            }

            // If master port is provided via cmd arguments
            if (Mst.Args.IsProvided(Mst.Args.Names.MasterPort))
            {
                masterPort = Mst.Args.MasterPort;
            }

            // Set the scene that player will be sent to is disconnected from server
            if (Mst.Options.Has(MstDictKeys.roomOfflineSceneName))
            {
                offlineScene = Mst.Options.AsString(MstDictKeys.roomOfflineSceneName);
            }
        }
コード例 #2
0
    protected virtual void Start()
    {
        _connection = GetConnection();
        _connection.StatusChanged += UpdateStatusView;

        UpdateStatusView(_connection.Status);
    }
コード例 #3
0
        /// <summary>
        /// WSClient
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <param name="subProtocol"></param>
        /// <param name="origin"></param>
        /// <param name="bufferSize"></param>
        public WSClient(string ip = "127.0.0.1", int port = 16666, string subProtocol = SubProtocolType.Default, string origin = "", int bufferSize = 10 * 1024)
        {
            _serverIP   = ip;
            _serverPort = port;

            if (string.IsNullOrEmpty(_url))
            {
                _url = $"ws://{ip}:{port}/";
            }

            _origin = origin;

            _wsContext = new WSContext();

            var option = SocketOptionBuilder.Instance
                         .UseIocp(_wsContext)
                         .SetIP(ip)
                         .SetPort(port)
                         .SetReadBufferSize(bufferSize)
                         .SetReadBufferSize(bufferSize)
                         .Build();

            _subProtocol = subProtocol;

            _client = SocketFactory.CreateClientSocket(option);

            _client.OnReceive      += _client_OnReceive;
            _client.OnDisconnected += WSClient_OnDisconnected;
            _client.OnError        += WSClient_OnError;
        }
コード例 #4
0
 private static void _timers_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
 {
     if (!_needReConnecting)
     {
         Console.WriteLine("dont need to connect againg.");
         return;
     }
     _needReConnecting = false;
     Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}:ThreadState:{Thread.CurrentThread.ThreadState}, Reconnecting to Server.");
     if (_client == null)
     {
         _client = _serviceProvider.GetRequiredService <IClientSocket>();
     }
     if (!_client.IsConnected)
     {
         Task.Run(async() => await _client.ConnectAsync(_serverConfig.IpAddress, _serverConfig.Port))
         .ContinueWith(tresult =>
         {
             if (tresult.Status == TaskStatus.Faulted)
             {
                 _needReConnecting = true;
                 Console.WriteLine($"{Task.CurrentId} status changed to  {_needReConnecting}.");
             }
             else
             {
                 Console.WriteLine("Successfully connected to the Server.");
             }
         });
     }
 }
コード例 #5
0
 /// <summary>
 ///     Sends a login request, using given credentials
 /// </summary>
 public void LogIn(string username, string password, LoginCallback callback, IClientSocket connection)
 {
     LogIn(new Dictionary <string, string> {
         { "username", username },
         { "password", password }
     }, callback, connection);
 }
コード例 #6
0
 public Client()
 {
     clientSocket              = new ClientSocket();
     clientSocket.OnException += e => { OnException?.Invoke(e); };
     UserInfo = new User_Client();
     LOCK     = new object();
 }
コード例 #7
0
ファイル: ClientMessageHandler.cs プロジェクト: roffster/WuSS
 public ClientMessageHandler(IClientSocket clientSocket, IMessageDecoder messageDecoder,ThreadSafeBuffer buffer)
 {
     _clientSocket = clientSocket;
     _messageDecoder = messageDecoder;
     _buffer = buffer;
     _clientSocket.BeginReceive(ReceiveMessage);
 }
コード例 #8
0
        public RClient(Uri uri)
        {
            if (string.IsNullOrEmpty(uri.Scheme) || string.Compare(uri.Scheme, "rpc", true) != 0)
            {
                ExceptionCollector.Add("Consumer.RClient.Init Error", new RPCSocketException("当前连接协议不正确,请使用格式rpc://ip:port"));
                return;
            }

            var ipPort = DNSHelper.GetIPPort(uri);

            _RContext = new RContext();

            SocketOptionBuilder builder = SocketOptionBuilder.Instance;

            var option = builder.SetSocket()
                         .UseIocp(_RContext)
                         .SetIP(ipPort.Item1)
                         .SetPort(ipPort.Item2)
                         .SetReadBufferSize()
                         .SetWriteBufferSize()
                         .Build();

            _client = SocketFactory.CreateClientSocket(option);

            _client.OnReceive += OnReceived;

            _client.OnDisconnected += _client_OnDisConnected;
        }
コード例 #9
0
ファイル: MsfAuthClient.cs プロジェクト: Orav/MSF_test
 /// <summary>
 /// Sends a request to server, to log in as a guest
 /// </summary>
 public void LogInAsGuest(LoginCallback callback, IClientSocket connection)
 {
     LogIn(new Dictionary <string, string>()
     {
         { "guest", "" }
     }, callback, connection);
 }
コード例 #10
0
 /// <summary>
 /// Synchronized (thread-safe) way of adding a new socket to the client list.
 /// </summary>
 /// <param name="socket"></param>
 /// <returns></returns>
 protected virtual bool AddClient(IClientSocket socket)
 {
     lock (Clients) {
         Clients.Add(socket);
     }
     return(false);
 }
コード例 #11
0
ファイル: SpawnerPlugin.cs プロジェクト: Avatarchik/SpeedDate
        public SpawnerPlugin(IClientSocket connection) : base(connection)
        {
            _locallyCreatedSpawners = new Dictionary <int, SpawnerController>();
            _freePorts = new Queue <int>();

            IsSpawnedProccess = CommandLineArgs.IsProvided(CommandLineArgs.Names.SpawnCode);
        }
コード例 #12
0
 void Start()
 {
     Text        = gameObject.GetComponent <Text>();
     _connection = GetConnection();
     _connection.StatusChanged += OnStatusChanged;
     OnStatusChanged(_connection.Status);
 }
コード例 #13
0
ファイル: MsfAuthClient.cs プロジェクト: GeeJD85/MSF_Custom
 /// <summary>
 /// Sends a request to server, to log in as a guest
 /// </summary>
 public void SignInAsGuest(SignInCallback callback, IClientSocket connection)
 {
     SignIn(new Dictionary <string, string>()
     {
         { "guest", string.Empty }
     }, callback, connection);
 }
コード例 #14
0
ファイル: MsfRoomsServer.cs プロジェクト: Miapata/GPE104
        /// <summary>
        /// Sends a request to register a room to master server
        /// </summary>
        public void RegisterRoom(RoomOptions options, RoomCreationCallback callback, IClientSocket connection)
        {
            if (!Connection.IsConnected)
            {
                callback.Invoke(null, "Not connected");
                return;
            }

            Connection.SendMessage((short)MsfOpCodes.RegisterRoom, options, (status, response) =>
            {
                if (status != ResponseStatus.Success)
                {
                    // Failed to register room
                    callback.Invoke(null, response.AsString("Unknown Error"));
                    return;
                }

                var roomId = response.AsInt();

                var controller = new RoomController(roomId, Connection, options);

                // Save the reference
                _localCreatedRooms[roomId] = controller;

                callback.Invoke(controller, null);

                // Invoke event
                if (RoomRegistered != null)
                {
                    RoomRegistered.Invoke(controller);
                }
            });
        }
コード例 #15
0
        public MsfSpawnersServer(IClientSocket connection) : base(connection)
        {
            _locallyCreatedSpawners = new Dictionary <string, SpawnerController>();
            _freePorts = new Queue <int>();

            IsSpawnedProccess = Msf.Args.IsProvided(Msf.Args.Names.SpawnCode);
        }
コード例 #16
0
        /// <summary>
        /// Raised when a client connects successfully
        /// </summary>
        /// <param name='client'>
        ///
        /// </param>
        public override void OnConnect(IClientSocket client)
        {
            base.OnConnect(client);

            // set it to asynchronous mode
            client.OnReceivedInvokeAsynchronously = true;
        }
コード例 #17
0
        /// <summary>
        /// This should be called from a process which is spawned.
        /// For example, it can be called from a game server, which is started by the spawner
        /// On successfull registration, callback contains <see cref="SpawnTaskController"/>, which
        /// has a dictionary of properties, that were given when requesting a process to be spawned
        /// </summary>
        public void RegisterSpawnedProcess(string spawnId, string spawnCode, RegisterSpawnedProcessCallback callback,
                                           IClientSocket connection)
        {
            if (!connection.IsConnected)
            {
                callback.Invoke(null, "Not connected");
                return;
            }

            //Debug.LogError("SPWn code: " + spawnCode);
            var packet = new RegisterSpawnedProcessPacket()
            {
                SpawnCode = spawnCode,
                SpawnId   = spawnId
            };

            connection.SendMessage((short)MsfOpCodes.RegisterSpawnedProcess, packet, (status, response) =>
            {
                if (status != ResponseStatus.Success)
                {
                    callback.Invoke(null, response.AsString("Unknown Error"));
                    return;
                }

                var properties = new Dictionary <string, string>().FromBytes(response.AsBytes());

                var process = new SpawnTaskController(spawnId, properties, connection, spawnCode);

                callback.Invoke(process, null);
            });
        }
コード例 #18
0
ファイル: RoomClient.cs プロジェクト: Fzcpp/MST
        protected override void Awake()
        {
            if (doNotDestroyOnLoad)
            {
                // Find another instance of this behaviour
                var clientInstance = FindObjectOfType <RoomClient>();

                if (clientInstance != this)
                {
                    Destroy(gameObject);
                    return;
                }

                DontDestroyOnLoad(gameObject);
            }

            base.Awake();

            // Get connection to master
            masterConnection = Mst.Connection;

            // Create room client connection
            Connection = ConnectionFactory();

            // Listen to connection statuses
            Connection.AddConnectionListener(OnClientConnectedToRoomServer, false);
            Connection.AddDisconnectionListener(OnClientDisconnectedFromRoomServer, false);

            // If master IP is provided via cmd arguments
            masterIP = Mst.Args.AsString(Mst.Args.Names.MasterIp, masterIP);
            // If master port is provided via cmd arguments
            masterPort = Mst.Args.AsInt(Mst.Args.Names.MasterPort, masterPort);
        }
コード例 #19
0
        public QClient(string name, int bufferSize = 100 * 1024, string ip = "127.0.0.1", int port = 39654)
        {
            _name = name;

            HeartSpan = 1000 * 1000;

            HeartAsync();

            _batcher = new Batcher <byte[]>(3000, 10); //此参数用于控制产生或消费速读,过大会导致溢出异常

            _batcher.OnBatched += _batcher_OnBatched;


            _qUnpacker = new QUnpacker();

            _queueCoder = new QueueCoder();

            ISocketOption socketOption = SocketOptionBuilder.Instance.SetSocket(Sockets.Model.SAEASocketType.Tcp)
                                         .UseIocp <QUnpacker>()
                                         .SetIP(ip)
                                         .SetPort(port)
                                         .SetWriteBufferSize(bufferSize)
                                         .SetReadBufferSize(bufferSize)
                                         .ReusePort(false)
                                         .Build();

            _clientSocket = SocketFactory.CreateClientSocket(socketOption);

            _clientSocket.OnReceive += _clientSocket_OnReceive;

            _clientSocket.OnError += _clientSocket_OnError;

            _clientSocket.OnDisconnected += _clientSocket_OnDisconnected;
        }
コード例 #20
0
        /// <summary>
        /// Sends a request to server, to ask for an e-mail confirmation code
        /// </summary>
        public void RequestEmailConfirmationCode(SuccessCallback callback, IClientSocket connection)
        {
            if (!connection.IsConnected)
            {
                callback.Invoke(false, "Not connected to server");
                return;
            }

            if (!IsSignedIn)
            {
                callback.Invoke(false, "You're not logged in");
                return;
            }

            connection.SendMessage((short)MstMessageCodes.GetEmailConfirmationCode, (status, response) =>
            {
                if (status != ResponseStatus.Success)
                {
                    callback.Invoke(false, response.AsString("Unknown error"));
                    return;
                }

                callback.Invoke(true, null);
            });
        }
コード例 #21
0
ファイル: RClient.cs プロジェクト: yswenli/SAEA
        public RClient(Uri uri, int timeOut = 3000)
        {
            if (string.IsNullOrEmpty(uri.Scheme) || string.Compare(uri.Scheme, "rpc", true) != 0)
            {
                ExceptionCollector.Add("Consumer.RClient.Init Error", new RPCSocketException("当前连接协议不正确,请使用格式rpc://ip:port"));
                return;
            }

            _timeOut = timeOut;

            _disorderSyncHelper = new DisorderSyncHelper(_timeOut);

            var ipPort = DNSHelper.GetIPPort(uri);

            _rUnpacker = new RUnpacker();

            SocketOptionBuilder builder = SocketOptionBuilder.Instance;

            var option = builder.SetSocket()
                         .UseIocp <RUnpacker>()
                         .SetIP(ipPort.Item1)
                         .SetPort(ipPort.Item2)
                         .SetReadBufferSize(10240)
                         .SetWriteBufferSize(10240)
                         .SetTimeOut(_timeOut)
                         .Build();

            _client = SocketFactory.CreateClientSocket(option);

            _client.OnReceive += OnReceived;

            _client.OnDisconnected += _client_OnDisConnected;
        }
コード例 #22
0
 public override void OnReceived(IClientSocket client, ICommand command)
 {
     // this must get called if you wish to handle specific command-type event handlers,
     // via the AddReceventEventHandler method call, otherwise, each command will arrive
     // at this point and would need to be delegated manually.
     base.OnReceived(client, command);
 }
コード例 #23
0
        /// <summary>
        ///     Sends a request to master server, to spawn a process in a given region, and with given options
        /// </summary>
        public void RequestSpawn(Dictionary <string, string> options, string region, ClientSpawnRequestCallback callback,
                                 IClientSocket connection)
        {
            if (!connection.IsConnected)
            {
                callback.Invoke(null, "Not connected");
                return;
            }

            var packet = new ClientsSpawnRequestPacket {
                Options = options,
                Region  = region
            };

            connection.SendMessage((short)MsfOpCodes.ClientsSpawnRequest, packet, (status, response) => {
                if (status != ResponseStatus.Success)
                {
                    callback.Invoke(null, response.AsString("Unknown error"));
                    return;
                }

                // Spawn id
                var spawnId = response.AsInt();

                var controller = new SpawnRequestController(spawnId, connection, options);

                _localSpawnRequests[controller.SpawnId] = controller;

                callback.Invoke(controller, null);
            });
        }
コード例 #24
0
        /// <summary>
        /// Sends a request to destroy a room of a given room id
        /// </summary>
        public void DestroyRoom(int roomId, SuccessCallback callback, IClientSocket connection)
        {
            if (!connection.IsConnected)
            {
                callback.Invoke(false, "Not connected");
                return;
            }

            connection.SendMessage((short)OpCodes.DestroyRoom, roomId, (status, response) =>
            {
                if (status != ResponseStatus.Success)
                {
                    callback.Invoke(false, response.AsString("Unknown Error"));
                    return;
                }

                _localCreatedRooms.TryGetValue(roomId, out var destroyedRoom);
                _localCreatedRooms.Remove(roomId);

                callback.Invoke(true, null);

                // Invoke event
                if (destroyedRoom != null)
                {
                    RoomDestroyed?.Invoke(destroyedRoom);
                }
            });
        }
コード例 #25
0
 // Use this for initialization
 void Start()
 {
     Text        = gameObject.GetComponent <Text>();
     _connection = GetConnection();
     _connection.StatusChanged += UpdateStatusView;
     UpdateStatusView(_connection.Status);
 }
コード例 #26
0
        /// <summary>
        ///     Sends a request to server, retrieves all profile values, and applies them to a provided
        ///     profile
        /// </summary>
        public void FillProfileValues(ObservableServerProfile profile, SuccessCallback callback,
                                      IClientSocket connection)
        {
            if (!connection.IsConnected)
            {
                callback.Invoke(false, "Not connected");
                return;
            }

            connection.SendMessage((short)MsfOpCodes.ServerProfileRequest, profile.Username, (status, response) => {
                if (status != ResponseStatus.Success)
                {
                    callback.Invoke(false, response.AsString("Unknown error"));
                    return;
                }

                // Use the bytes received, to replicate the profile
                profile.FromBytes(response.AsBytes());

                profile.ClearUpdates();

                _profiles[profile.Username] = profile;

                profile.ModifiedInServer += serverProfile => { OnProfileModified(profile, connection); };

                profile.Disposed += OnProfileDisposed;

                callback.Invoke(true, null);
            });
        }
コード例 #27
0
        protected override void Awake()
        {
            base.Awake();

            // If current object is destroying just make a return
            if (isNowDestroying)
            {
                return;
            }

            logger          = Mst.Create.Logger(typeof(ClientToMasterConnector).Name);
            logger.LogLevel = logLevel;

            // Set connection if it is null
            if (Connection == null)
            {
                Connection = ConnectionFactory();
            }

            // In case this object is not at the root level of hierarchy
            // move it there, so that it won't be destroyed
            if (transform.parent != null)
            {
                transform.SetParent(null, false);
            }

            if (Mst.Args.StartClientConnection)
            {
                connectOnStart = true;
            }
        }
コード例 #28
0
        public void DisconnectClient(string ip)
        {
            if (!IsRunning)
            {
                OnDisconnectClientCompletedEvent?.Invoke(ip, SocketServerResult.ServerNotRunning);

                return;
            }

            SocketServerResult sRes = SocketServerResult.None;

            try
            {
                IClientSocket client = this[ip];

                client.Close();

                _clientDic.Remove(ip);

                sRes = SocketServerResult.Success;
            }
            catch
            {
                sRes = SocketServerResult.Exception;
            }
            finally
            {
                OnDisconnectClientCompletedEvent?.Invoke(ip, sRes);
            }
        }
コード例 #29
0
        /// <summary>
        ///     Sends a request to master server, to register an existing spawner with given options
        /// </summary>
        public void RegisterSpawner(SpawnerOptions options, RegisterSpawnerCallback callback,
                                    IClientSocket connection)
        {
            if (!connection.IsConnected)
            {
                callback.Invoke(null, "Not connected");
                return;
            }

            connection.SendMessage((short)MsfOpCodes.RegisterSpawner, options, (status, response) => {
                if (status != ResponseStatus.Success)
                {
                    callback.Invoke(null, response.AsString("Unknown Error"));
                    return;
                }

                var spawnerId = response.AsInt();

                var controller = new SpawnerController(spawnerId, connection, options);

                // Save reference
                _locallyCreatedSpawners[spawnerId] = controller;

                callback.Invoke(controller, null);

                // Invoke the event
                if (SpawnerRegistered != null)
                {
                    SpawnerRegistered.Invoke(controller);
                }
            });
        }
コード例 #30
0
 public SpawnTaskController(string spawnId, Dictionary <string, string> properties, IClientSocket connection, string spawnCode)
 {
     this.spawnCode = spawnCode;
     _connection    = connection;
     SpawnId        = spawnId;
     Properties     = properties;
 }
コード例 #31
0
ファイル: MessageClient.cs プロジェクト: ywscr/SAEA
        public MessageClient(int bufferSize = 102400, string ip = "127.0.0.1", int port = 39654)
        {
            _messageContext = new MessageContext();

            var option = SocketOptionBuilder.Instance
                         .SetSocket()
                         .UseIocp(_messageContext)
                         .SetIP(ip)
                         .SetPort(port)
                         .SetReadBufferSize(bufferSize)
                         .SetWriteBufferSize(bufferSize)
                         .Build();

            _client = SocketFactory.CreateClientSocket(option);

            _client.OnReceive += _client_OnReceive;

            HeartSpan = 10 * 1000;

            HeartAsync();

            _batcher = new Batcher(10000, 10);

            _batcher.OnBatched += _batcher_OnBatched;
        }
コード例 #32
0
 public void setDelegate(IClientSocket callBack)
 {
     _callBack = callBack;
 }
コード例 #33
0
 public void Dispose()
 {
     if (_client != null) {
         _client.Close();
         _client = null;
     }
 }
コード例 #34
0
 public Request(IClientSocket client, char[] data)
 {
     _data = data;
     _client = client;
 }
コード例 #35
0
 public void Setup()
 {
     _socket = MockRepository.GenerateMock<IClientSocket>();
 }
コード例 #36
0
        // Use this for initialization
        // ReSharper disable once UnusedMember.Local
        void Start()
        {
            Instance = gameObject;
            //_loaderImage = GameObject.Find("LoaderImage");
            //_levelText = GameObject.Find("LevelText").GetComponent<Text>();
            GameBoard.enabled = false;
            ActionBoard.enabled = true;
            ActionPanelScrollbar.value = 0;
            BuildingPanelScrollbar.value = 0;
            ResizeBuildingPanel();
            InitBuildingTiles();

            //after everything is set up, THEN start game
            ClientSocket = UIScripts.ClientSocket.Instance;
            ClientSocket.StartGame(1);
        }