public void InvokeClientConnect(XeonClient client) { if (OnClientConnect != null) { OnClientConnect.Invoke(client); } }
public IEnumerator <YieldInstruction> Update() { var count = 0; while (cancelSource == null || !cancelSource.Token.IsCancellationRequested) { bool isStartNotify = false; lock (this){ isStartNotify = isStartNotifyRequested; } if (isStartNotify) { onStart(cancelSource); } do { AcceptData acceptData = null; lock (this){ acceptData = accepted.Count > 0 ? accepted.Dequeue() : null; count = accepted.Count; } if (acceptData != null) { onConnect?.Invoke(acceptData.connectionIndex, acceptData.sender); } } while(count > 0); yield return(new WaitForEndOfFrame()); } }
/// <summary> /// Обработчик события при попытке принять входящее соединение /// </summary> /// <param name="sender"></param> /// <param name="socketArgs"></param> private void AcceptSocketOnCompleted(object sender, SocketAsyncEventArgs socketArgs) { if (socketArgs.SocketError != SocketError.Success) { return; } lock (HandlerSockets) { _currentClientId = Guid.NewGuid(); var hSocket = new HandlerSocket(socketArgs.AcceptSocket, _currentClientId); HandlerSockets.Add(_currentClientId, hSocket); OnClientConnect?.Invoke(_currentClientId); } try { AwaitRecieveData(_currentClientId); var argsAcceptSocket = new SocketAsyncEventArgs(); argsAcceptSocket.Completed += AcceptSocketOnCompleted; _listenerSocket.AcceptAsync(argsAcceptSocket); } catch (SocketException socketException) { OnClientDisconnect?.Invoke(_currentClientId); Debug.WriteLine(socketException.Message); } }
public void AddClient(Client client) { client.OnPacketReceive += Client_OnPacketReceive; client.OnDisconnect += Client_OnDisconnect; ConnectedClients.TryAdd(client.NetworkId, client); OnClientConnect?.Invoke(this, new ClientStateChangeArgs(client.NetworkId, client)); }
public void AcceptCallback(IAsyncResult ar) { //if (listener.Connected) FnOnMessage("Client is Connected..."); //else // return; // Get the socket that handles the client request. //Socket listener = (Socket)ar.AsyncState; try { if (listener.IsDisposed) { return; } Socket handler = listener.EndAccept(ar); // Create the state object. StateObject state = new StateObject(); state.workSocket = handler; OnClientConnect?.Invoke(this, handler); FnOnMessage("Starting to Read..."); handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); FnOnMessage("Initilizing Next Client for connection..."); listener.BeginAccept(new AsyncCallback(AcceptCallback), listener); } catch (Exception ex) { FnOnMessage(ex.Message, ex); } }
private void Client_OnPacketReceive(object sender, ReceivePacketArgs e) { var client = (Client)sender; if (e.Packet is AuthenticationPacket) { var account = ((AuthenticationPacket)e.Packet).Account; if (AllowedAccounts.Contains(account)) { IPacket packet = new InformationPacket(); packet.Execute(client); } else { RemoveClient(client); } } else if (e.Packet is InformationPacket) { var info = ((InformationPacket)e.Packet); client.NetworkId = info.NetworkId; AddClient(client); OnClientConnect?.Invoke(this, new ClientStateChangeArgs(client.NetworkId, client, info)); } else { OnClientPacketReceive?.Invoke(this, e); } }
private void OnConnected(NetworkMessage msg) { Log("Connected to server"); if (OnClientConnect != null) { OnClientConnect.Invoke(""); } }
private void HandleAccept(IAsyncResult AR) { Socket s = NetworkSocket.EndAccept(AR); ConnectedClient c = new ConnectedClient(s); OnClientConnect?.Invoke(c); NetworkSocket.BeginAccept(OnAcceptCallback, null); }
public virtual async Task StartAsync(CancellationToken token) { if (IsListening || Starting || Stopping) { return; } try { Starting = true; TcpListener = new ExtendedTcpListener(IpEndpoint); TcpListener.Start(); Starting = false; OnStart?.Invoke(this); while (!Stopping) { var client = ClientFactory.Create(await TcpListener.AcceptTcpClientAsync()); foreach (var handler in Handlers.Values) { client.AddHandler(handler); } Clients.Add(client.Id, client); OnClientConnect?.Invoke(client); client.ListenAsync(token); } } catch (SocketException se) when(Stopping) { Logger.LogTrace(se, $"Ignoring exception because listener is in shutdown mode."); } catch (SocketException se) { Logger.LogTrace(se, $"SocketException.ErrorCode: {se.ErrorCode}"); throw; } catch (ObjectDisposedException ode) when(Stopping || TcpListener == null) { Logger.LogTrace(ode, $"Ignoring exception because listener is in shutdown mode."); } catch (ArgumentNullException) when(Starting) { throw; } catch (Exception e) { Logger.LogError(e, e.Message); } finally { Starting = false; } }
/// <summary> /// Update is called every frame. /// If there is data to receive it will receive this data and transforms it into a packet, which will be send to the corresponding client handler /// </summary> void Update() { //check for input while (_server.Available > 0) { //receive data and create a packet out of the data byte[] bytesReceived = _server.Receive(ref _endPoint); Packet packet = new Packet(bytesReceived); //get the endpoint from the sender IPEndPoint endPoint = new IPEndPoint(_endPoint.Address, _endPoint.Port); //check if the sender is already connected or if it was someone new if (!_connectedClients.ContainsKey(endPoint) && _connectedClients.Count < 2) { //create a new client handler with the new address and port Debug.Log("Someone new connected"); ClientHandler clientHandler = new ClientHandler(this, endPoint.Address, endPoint.Port, _clientNetworkID++); //add the new client handler to the list of the connected clients _connectedClients.Add(endPoint, clientHandler); _clientHandlers = _connectedClients.Values; //create a packet tracker, which will track the communication between the first connected client and the server if (_connectedClients.Count == 1) { _tracker = new PacketTracker(clientHandler, _totalPacketsSendText, _totalPacketsLostText, _packetsSendLastSecondText, _packetsLostLastSecondText, _lostPacketParent, _sendPacketParent, _displayPrefab); InvokeRepeating("UpdateTracker", 1f, 1f); } //call the OnClientCOnnected event if it is not null OnClientConnect?.Invoke(clientHandler); } //tell the correct client handler to handle the packet _connectedClients[endPoint].HandleInput(packet); Debug.Log("I received a message: " + endPoint.Port); } //tell each client handler to check their packets send to see which packets did time out if (_clientHandlers != null) { foreach (ClientHandler clientHandler in _clientHandlers) { //clientHandler.SendTestPacket(); clientHandler.CheckPacketsSend(); } } //update the tracker if it was created _tracker?.Update(); }
public async void ConnectClientAsync(TcpClient tcpClient) { await Task.Factory.StartNew(() => { var client = new Connection(tcpClient); SubscribeOnClient(client); client.Connect(); connections.Add(client); OnClientConnect.Invoke(client); }); }
void AcceptedClientConnection(Socket client) { clients.Add(client); IPEndPoint clientEndPoint = (IPEndPoint)client.RemoteEndPoint; DebugLog.Info($"TcpServerSocket::AcceptedClientConnection->New client connection accepted ({clientEndPoint.Address}:{clientEndPoint.Port})"); OnClientConnect?.Invoke(this, new TcpSocketEventArgs(client)); StartReceiving(client); }
void AcceptedClientConnection(Socket client) { clients.Add(client); IPEndPoint clientEndPoint = (IPEndPoint)client.RemoteEndPoint; NetUtil.LogInfo(logTag, $"New client connection accepted ({clientEndPoint.Address}:{clientEndPoint.Port})"); OnClientConnect?.Invoke(this, new TcpSocketEventArgs(client)); StartReceiving(client); }
private void HandleAccept(IAsyncResult ar) { try { Socket s = NetworkSocket.EndAccept(ar); OnClientConnect?.Invoke(this, s); } catch (Exception ex) { LastError = ex; Close(); return; } NetworkSocket.BeginAccept(InternalAcceptHandler, null); }
private void ExtendedClientEnterView(object sender, IEnumerable <ClientEnterView> eventArgs) { clientbufferOutdated = true; if (OnClientConnect == null) { return; } foreach (var evData in eventArgs) { clientbufferOutdated = true; OnClientConnect?.Invoke(sender, evData); } }
private void TcpSock_OnClientConnect(BaseServerSocket sender, Socket s) { var client = new InternalSyncIOConnectedClient(s, _packager); client.SetID(_guidGenerator()); client.BeginReceve(ReceveHandler); client.Send(cl => { Clients.Add(cl); client.OnDisconnect += (c, err) => Clients.Remove(c); OnClientConnect?.Invoke(this, cl);//Trigger event after handshake packet has been sent. }, new HandshakePacket(client.ID, true)); }
private void CallClientConnect(int clientId) { try { OnClientConnect?.Invoke(this, new ConnectionArgs(clientId)); } catch (Exception ex) { if (_showFail) { Debug.Fail(ex.Message, ex.StackTrace); } } }
public void AcceptCallback(IAsyncResult ar) { allDone.Set(); if (OnlineSocket == null) { OnlineSocket = new List <Socket>(); } if (listener == null) { return; } Socket handler = listener.EndAccept(ar); CountOfClinetChange?.Invoke(); LogRecived?.Invoke(LogTypes.ClientConnected, string.Format("Client {0} is now connected", handler.IpAdress())); if (!OnlineSocket.Contains(handler)) { //OnlineSocket.ForEach(x => //{ // if (x!=null && x.IpAdress() == handler.IpAdress()) // x = null; //}); for (int i = 0; i < OnlineSocket.Count; i++) { if (OnlineSocket[i] != null) { if (OnlineSocket[i].IpAdress() == handler.IpAdress()) { OnlineSocket[i] = null; } } } OnlineSocket.Add(handler); OnClientConnect?.Invoke(handler.IpAdress()); } // Create the state object. StateObject state = new StateObject(); state.workSocket = handler; handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); }
private void TcpSock_OnClientConnect(BaseServerSocket sender, Socket s) { InternalSecureSocketConnectedClient client = new InternalSecureSocketConnectedClient(s, _packager); client.SetId(_guidGenerator()); client.BeginReceive(ReceiveHandler); client.Send(cl => { Clients.Add(cl); client.OnDisconnect += (c, err) => { Clients.Remove(c); }; OnClientConnect?.Invoke(this, cl); }, new HandshakePacket(true, client.Id)); }
private void HandleConnection() { try { while (true) { //Check status of current connections lock (_lock) { foreach ((string key, ClientSocket socket) in _clientSockets.ToList().Where(x => !x.Value.IsConnected())) { socket.Disconnect(); _clientSockets.Remove(key); OnClientDisconnect?.Invoke(socket.ClientId); } } //Check for new connections if (_listener.Pending()) { //Accept new client ClientSocket newSocket = new ClientSocket(Guid.NewGuid().ToString(), _listener.AcceptTcpClient()); //Add new client to list lock (_lock) { _clientSockets.Add(newSocket.ClientId, newSocket); } OnClientConnect?.Invoke(newSocket); //Fire client connection and authentication events newSocket.Emit("connect"); newSocket.Emit("authentication"); } else { //Waits half a second if no pending connections to preserve performance of machine Thread.Sleep(500); } } } catch (SocketException e) { Console.WriteLine("SocketException: {0}", e); Stop(); } }
public FizzySteamyMirror() { // dispatch the events from the server server.OnConnected += (id) => OnServerConnect?.Invoke(id); server.OnDisconnected += (id) => OnServerDisconnect?.Invoke(id); server.OnReceivedData += (id, data) => OnServerData?.Invoke(id, data); server.OnReceivedError += (id, exception) => OnServerError?.Invoke(id, exception); // dispatch events from the client client.OnConnected += () => OnClientConnect?.Invoke(); client.OnDisconnected += () => OnClientDisconnect?.Invoke(); client.OnReceivedData += (data) => OnClientData?.Invoke(data); client.OnReceivedError += (exception) => OnClientError?.Invoke(exception); Debug.Log("FizzySteamyMirror initialized!"); }
/// <summary> /// Confirms that a clients received its identification and dispatches a new client event. /// </summary> void WelcomeResponse(Packet packet) { var idInPacket = packet.ReadInt(); var username = packet.ReadString(); Debug.Log($"Welcome Received for client id: {Id} and username: {username}"); if (Id == idInPacket) { OnClientConnect.Invoke(this); } else { Debug.Log($"(ID: {Id}) has assumed the wrong client ID ({idInPacket})!"); Disconnect(); } }
private void EnqueueIncomingPacket(NetWrapper netWrapper, uint binaryAddress, PacketId packetId, byte[] data) { if (!this.clients[netWrapper].ContainsKey(binaryAddress)) { this.clients[netWrapper][binaryAddress] = new Client(binaryAddress, netWrapper); OnClientConnect?.Invoke(this.clients[netWrapper][binaryAddress]); } this.packetReducer.EnqueuePacket(this.clients[netWrapper][binaryAddress], packetId, data); if (packetId == PacketId.PACKET_ID_PLAYER_QUIT || packetId == PacketId.PACKET_ID_PLAYER_TIMEOUT) { this.clients[netWrapper][binaryAddress].IsConnected = false; OnClientDisconnect?.Invoke(this.clients[netWrapper][binaryAddress]); this.clients[netWrapper].Remove(binaryAddress); } }
public void ListenLoop(object arg) { ClientStore clients = arg as ClientStore; if (clients != null) { while (!looper.LoopDone) { try { var res = ServerListenAsync(useLocalhost); if (res.IsFaulted || (res.Result == null)) { Console.WriteLine("Problem with connection."); } else { Console.WriteLine("Accepted Client Connection on port: {0}", CliServDefaults.DfltPort); Client client = new Client(res.Result, CliServDefaults.BufferSize, dataGetter); try { // Start the service loops client.Start(); ClientStore.AddClient(client, client.ClientHandle); OnClientConnect?.Invoke(client); } catch (Exception e) { Console.WriteLine("Client Add to List Exception: {0}", e.Message); } } } catch (Exception e) { Console.WriteLine(e.Message); } } if (_listenSocket.Connected) { _listenSocket.Shutdown(SocketShutdown.Both); _listenSocket.Close(); } Console.WriteLine("Listener Done."); } }
private void AcceptCallback(IAsyncResult ar) { CancellationToken cancellationToken = (CancellationToken)ar.AsyncState; _waiterConnection.Release(); Socket handler = _listenerSocket.EndAccept(ar); _logger.LogDebug($"Client connected - Handle: " + handler.Handle); var connection = _container.Resolve <TCPConnection>(new TypedParameter(typeof(Socket), handler)); _connections.TryAdd(handler.Handle, connection); connection.OnReceivePacket += (s, e) => OnClientData?.Invoke(this, new Message((IConnection)s, e)); connection.OnDisconnect += (s, e) => OnClientDisconnect?.Invoke(this, (IConnection)s); OnClientConnect?.Invoke(this, connection); connection.StartListenData(cancellationToken, _options.Source, true); }
public WSServer(int port) { context = SynchronizationContext.Current; wss = new WebSocketServer(port); wss.AddWebSocketService <WSBehaviour>("/", behaviour => { behaviour.OnClientConnect += (id, ws) => { context.Post(_ => { OnClientConnect.Invoke(id, ws); }, null); }; behaviour.OnClientData += (ws, e) => { context.Post(_ => { if (e.IsText) { OnTextData.Invoke(ws, e.Data); } else if (e.IsBinary) { OnBinaryData.Invoke(ws, e.RawData); } }, null); }; behaviour.OnClientClose += (ws, e) => { context.Post(_ => { OnClientClose.Invoke(ws); }, null); }; behaviour.OnClientError += (id, e) => { context.Post(_ => { OnClientError.Invoke(id, e.Exception); }, null); }; }); }
/// <summary> /// An internal callback triggered when a client connects to the server. /// </summary> /// <param name="asyn"></param> private void OnReceiveConnection(IAsyncResult asyn) { try { lock (workerSockets) { Interlocked.Increment(ref _currentClientNumber); // Thread Safe UserSock us = new UserSock(_currentClientNumber, _mainSocket.EndAccept(asyn)); workerSockets.Add(_currentClientNumber, us); } OnClientConnect?.Invoke(_currentClientNumber); /* * if (_clientConnect != null) * _clientConnect(_currentClientNumber); */ WaitForData(_currentClientNumber); _mainSocket.BeginAccept(new AsyncCallback(OnReceiveConnection), null); } catch (ObjectDisposedException) { System.Console.WriteLine("OnClientConnection: Socket has been closed"); } catch (SocketException se) { //Console.WriteLine("SERVER EXCEPTION in OnReceiveConnection: " + se.Message); System.Diagnostics.Debug.WriteLine("SERVER EXCEPTION in OnReceiveConnection: " + se.Message);//pe 4-22-2015 if (workerSockets.ContainsKey(_currentClientNumber)) { Console.WriteLine("RemoteEndPoint: " + workerSockets[_currentClientNumber].UserSocket.RemoteEndPoint.ToString()); Console.WriteLine("LocalEndPoint: " + workerSockets[_currentClientNumber].UserSocket.LocalEndPoint.ToString()); Console.WriteLine("Closing socket from OnReceiveConnection"); } //Socket gets closed and removed from OnClientDisconnect if (OnClientDisconnect != null) { OnClientDisconnect(_currentClientNumber); } } }
/// <summary> /// Receive and process a single incoming packet. /// Returns 'true' if a packet was received, 'false' otherwise. /// </summary> private bool ProcessClientPacket(Buffer buffer, TcpProtocol client) { #if DEBUG Debug.Log("[Listener][TcpProtocol:ProcessClientPacket()] - Processing. Status: " + client.Status); #endif // If the player has not yet been verified, the first packet must be an ID request if (client.Status == ConnectionStatus.Verifying) { if (client.VerifyRequestID(buffer, true)) { #if DEBUG Debug.Log("[Listener][TcpProtocol:ProcessClientPacket()] - Client verified. Id: " + client.Id); #endif clientsDictionary.Add(client.Id, client); if (OnClientConnect != null) { OnClientConnect.Invoke(client.Id, client); } return(true); } RemoveClient(client); return(false); } if (client.Status == ConnectionStatus.Connected) { Debug.Log("[Listener][TcpProtocol:ProcessClientPacket()] - Packet received."); if (OnListenerPacketReceived != null) { OnListenerPacketReceived.Invoke(buffer, client); } } #if DEBUG Debug.Log("[Listener][TcpProtocol:ProcessClientPacket()] - Processed. Status: " + client.Status); #endif return(true); }
private async Task <bool> HttpServer_BeginRequest(HttpContext context, CancellationToken cancellationToken) { var request = context.Request; var response = context.Response; Core.Log.LibVerbose("Request received from {0}:{1} to {2} {3}", request.RemoteAddress, request.RemotePort, request.Method, request.RawUrl); var clientId = Guid.NewGuid(); var ccEvent = ClientConnectEventArgs.Retrieve(clientId); OnClientConnect?.Invoke(this, ccEvent); ClientConnectEventArgs.Store(ccEvent); context.Response.ContentType = Serializer.MimeTypes[0]; var responseBuffer = default(MultiArray <byte>); if (context.Request.Method == HttpMethod.GET && EnableGetDescriptors && OnGetDescriptorsRequest != null) { var eArgs = ServerDescriptorsEventArgs.Retrieve(); OnGetDescriptorsRequest(this, eArgs); responseBuffer = Serializer.Serialize(eArgs.Descriptors); ServerDescriptorsEventArgs.Store(eArgs); } if (context.Request.Method == HttpMethod.POST && !(OnMethodCallAsync is null)) { Counters.IncrementBytesReceived(context.Request.PostData.Length); var messageRq = Serializer.Deserialize <RPCRequestMessage>(context.Request.PostData); var eArgs = MethodEventArgs.Retrieve(clientId, messageRq, cancellationToken); await OnMethodCallAsync.InvokeAsync(this, eArgs).ConfigureAwait(false); if (eArgs.Response != null) { responseBuffer = Serializer.Serialize(eArgs.Response); OnResponseSent?.Invoke(this, eArgs.Response); } MethodEventArgs.Store(eArgs); } await responseBuffer.CopyToAsync(response.OutputStream).ConfigureAwait(false); Counters.IncrementBytesSent(responseBuffer.Count); return(true); }
/// <summary> /// An internal callback triggered when a client connects to the server. /// </summary> /// <param name="async"></param> private void OnReceiveConnection(IAsyncResult async) { try { lock (WorkerSockets) { Interlocked.Increment(ref _currentClientNumber); // Thread Safe var us = new UserSock(_currentClientNumber, _mainSocket.EndAccept(async)); WorkerSockets.Add(_currentClientNumber, us); } OnClientConnect?.Invoke(_currentClientNumber); WaitForData(_currentClientNumber); _mainSocket.BeginAccept(OnReceiveConnection, null); } catch (ObjectDisposedException) { Console.WriteLine(@"OnClientConnection: Socket has been closed"); } catch (SocketException se) { //Console.WriteLine("SERVER EXCEPTION in OnReceiveConnection: " + se.Message); Debug.WriteLine("SERVER EXCEPTION in OnReceiveConnection: " + se.Message); //pe 4-22-2015 if (WorkerSockets.ContainsKey(_currentClientNumber)) { Console.WriteLine(@"RemoteEndPoint: " + WorkerSockets[_currentClientNumber].UserSocket.RemoteEndPoint); Console.WriteLine(@"LocalEndPoint: " + WorkerSockets[_currentClientNumber].UserSocket.LocalEndPoint); Console.WriteLine(@"Closing socket from OnReceiveConnection"); } //Socket gets closed and removed from OnClientDisconnect OnClientDisconnect?.Invoke(_currentClientNumber); } }