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); } }
protected virtual void Start() { _connection = GetConnection(); _connection.StatusChanged += UpdateStatusView; UpdateStatusView(_connection.Status); }
/// <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; }
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."); } }); } }
/// <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); }
public Client() { clientSocket = new ClientSocket(); clientSocket.OnException += e => { OnException?.Invoke(e); }; UserInfo = new User_Client(); LOCK = new object(); }
public ClientMessageHandler(IClientSocket clientSocket, IMessageDecoder messageDecoder,ThreadSafeBuffer buffer) { _clientSocket = clientSocket; _messageDecoder = messageDecoder; _buffer = buffer; _clientSocket.BeginReceive(ReceiveMessage); }
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; }
/// <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); }
/// <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); }
public SpawnerPlugin(IClientSocket connection) : base(connection) { _locallyCreatedSpawners = new Dictionary <int, SpawnerController>(); _freePorts = new Queue <int>(); IsSpawnedProccess = CommandLineArgs.IsProvided(CommandLineArgs.Names.SpawnCode); }
void Start() { Text = gameObject.GetComponent <Text>(); _connection = GetConnection(); _connection.StatusChanged += OnStatusChanged; OnStatusChanged(_connection.Status); }
/// <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); }
/// <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); } }); }
public MsfSpawnersServer(IClientSocket connection) : base(connection) { _locallyCreatedSpawners = new Dictionary <string, SpawnerController>(); _freePorts = new Queue <int>(); IsSpawnedProccess = Msf.Args.IsProvided(Msf.Args.Names.SpawnCode); }
/// <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; }
/// <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); }); }
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); }
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; }
/// <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); }); }
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; }
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); }
/// <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); }); }
/// <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); } }); }
// Use this for initialization void Start() { Text = gameObject.GetComponent <Text>(); _connection = GetConnection(); _connection.StatusChanged += UpdateStatusView; UpdateStatusView(_connection.Status); }
/// <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); }); }
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; } }
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); } }
/// <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); } }); }
public SpawnTaskController(string spawnId, Dictionary <string, string> properties, IClientSocket connection, string spawnCode) { this.spawnCode = spawnCode; _connection = connection; SpawnId = spawnId; Properties = properties; }
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; }
public void setDelegate(IClientSocket callBack) { _callBack = callBack; }
public void Dispose() { if (_client != null) { _client.Close(); _client = null; } }
public Request(IClientSocket client, char[] data) { _data = data; _client = client; }
public void Setup() { _socket = MockRepository.GenerateMock<IClientSocket>(); }
// 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); }