private void OnClientConnected(AsynchronousSocket clientSocket) { if (ClientConnected != null) { ClientConnected.Invoke(clientSocket, new EventArgs()); } }
private void TcpListener_AcceptCallback(IAsyncResult ar) { if (!Listening) { return; } try { var newClient = (ar.AsyncState as TcpListener).EndAcceptSocket(ar); var clientWrapper = new ClientWrapper(newClient); clientWrapper.Disconnected += Client_Disconnected; Clients.Add(clientWrapper); clientWrapper.Start(); ClientConnected?.Invoke(clientWrapper); // Re-call BeginAcceptSocket _tcpListener.BeginAcceptSocket(TcpListener_AcceptCallback, _tcpListener); } catch (Exception ex) { ErrorOccured?.Invoke(ex); } }
/// <summary> /// Server startup method. /// </summary> /// <param name="port"></param> /// <param name="backlog"></param> /// <returns></returns> public async Task <CoreServerBase> StartAsync(int port, int backlog = 10) { if (port <= 0 || IsServerListerning) { return(this); } ServerPort = port; try { await ServerSemaphore.WaitAsync().ConfigureAwait(false); Logger.Log("Starting TCP Server..."); Server = new TcpListener(new IPEndPoint(IPAddress.Any, ServerPort)); Server.Start(backlog); Logger.Log($"Server waiting for connections at port -> {ServerPort}"); Helpers.InBackgroundThread(async() => { try { await ServerListerningSemaphore.WaitAsync().ConfigureAwait(false); while (!ExitRequested && Server != null) { IsServerListerning = true; if (!_isListernerEventFired) { ServerStarted?.Invoke(this, new OnServerStartedListerningEventArgs(IPAddress.Any, ServerPort, DateTime.Now)); _isListernerEventFired = true; } if (Server.Pending()) { TcpClient client = await Server.AcceptTcpClientAsync().ConfigureAwait(false); Connection clientConnection = new Connection(client, this); ClientConnected?.Invoke(this, new OnClientConnectedEventArgs(clientConnection.ClientIpAddress, DateTime.Now, clientConnection.ClientUniqueId)); await clientConnection.Init().ConfigureAwait(false); } await Task.Delay(1).ConfigureAwait(false); } IsServerListerning = false; } finally { ServerListerningSemaphore.Release(); } }, GetHashCode().ToString(), true); while (!IsServerListerning) { await Task.Delay(1).ConfigureAwait(false); } return(this); } finally { ServerSemaphore.Release(); } }
public ServerWorld(ServerOptions options) : base(options, new ServerWorldCreator(options)) { Options = options ?? throw new ArgumentNullException(nameof(options)); void OnWorldCreated() { NetCodeHookSystem hookSystem = World.GetHookSystem() ?? throw new InvalidOperationException(HookSystemDoesNotExistError); hookSystem.RegisterHook <ListeningEvent>(e => { ListenSuccess?.Invoke(); }); hookSystem.RegisterHook <ListenFailedEvent>(e => { ListenFailed?.Invoke(); }); hookSystem.RegisterHook <DisconnectingEvent>(e => { Closed?.Invoke(); }); hookSystem.RegisterHook <ClientConnectedEvent>(e => { ClientConnected?.Invoke(((ClientConnectedEvent)e).ConnectionEntity); }); hookSystem.RegisterHook <ClientDisconnectedEvent>(e => { ClientDisconnected?.Invoke(((ClientDisconnectedEvent)e).NetworkId); }); } WorldCreated += OnWorldCreated; if (WorldCreator.WorldIsCreated) { OnWorldCreated(); } }
async Task Run(TaskCompletionSource <bool> tcs) { try { listener = new TcpListener(IPAddress.Any, serverPort); listener.Start(); } catch (Exception ex) { tcs.SetException(ex); } Log.Information($"Tcp server listening at port {serverPort}"); tcs.SetResult(true); // Loop for (; ;) { var client = await listener.AcceptTcpClientAsync(); var token = new CancellationTokenSource(); Receive(client, token.Token); var guid = Guid.NewGuid(); clients[guid] = new Tuple <TcpClient, CancellationTokenSource>(client, token); Log.Information("New client connection"); ClientConnected?.Invoke(this, null); } }
public void AcceptCallback(IAsyncResult ar) { // Signal the main thread to continue. accpeting.Set(); try { Socket listener = (Socket)ar.AsyncState; Socket handler = listener.EndAccept(ar); ConnectedClient connectedClient = new ConnectedClient(); connectedClient.workSocket = handler; connectedClient.id = Guid.NewGuid(); lock (clients) { clients.Add(connectedClient); } ClientConnected?.Invoke(connectedClient); handler.BeginReceive(connectedClient.buffer, 0, ConnectedClient.BufferSize, 0, new AsyncCallback(ReadCallback), connectedClient); } catch (Exception e) { Logger.Debug(e.ToString()); } }
private void AcceptCallback(IAsyncResult ar) { try { Socket listener = (Socket)ar.AsyncState; Socket handler = listener.EndAccept(ar); ConnectedClient connectedClient = new ConnectedClient(); connectedClient.workSocket = handler; connectedClient.id = Guid.NewGuid(); lock (clients) { clients.Add(connectedClient); } ClientConnected?.Invoke(connectedClient); handler.BeginReceive(connectedClient.buffer, 0, ConnectedClient.BufferSize, 0, new AsyncCallback(ReadCallback), connectedClient); } catch (ObjectDisposedException) { Logger.Debug("ObjectDisposedException in Server AcceptCallback. This is expected during server shutdowns, such as during address verification"); } catch (Exception e) { Logger.Debug(e.ToString()); } }
public override Task OnConnectedAsync() { _users.TryAdd(Context.ConnectionId, Context.ConnectionId); ClientConnected?.Invoke(Context.ConnectionId); return(base.OnConnectedAsync()); }
public void OnClientConnected(string clientId) { var client = new Client(clientId); _clients.Add(client); ClientConnected?.Invoke(client); }
private void ListenLoop(object o) { try { Debug.Message("EventServer의 배경쓰레드에서 반복문 진입."); while (!Halted) { TcpClient client = mListener.AcceptTcpClient(); EventClient eventClient = new EventClient(client, true); if (eventClient == null ? false : eventClient.IsOnline) { eventClient.Disconnected += HandleClientDisconnection; Clients.Add(eventClient); ClientConnected?.Invoke(this, new ClientConnectedEventArgs(eventClient)); } } } catch (Exception e) { Debug.Error($"EventServer의 배경쓰레드에서 예외 발생 : {e.Message}\n\n{e.StackTrace}"); Halt(); } finally { Debug.Message($"EventServer의 배경쓰레드에서 finally절 진입함."); // Halt 되었으므로 쓰레드가 정리됨. } }
private void Listen() { ThreadPool.QueueUserWorkItem(_ => { while (_isListening) { var session = new WebSocketSession(_tcpListener.AcceptTcpClient()); session.HandshakeCompleted += (__, ___) => { Console.WriteLine($"{session.Id}| Handshake Valid."); Clients.Add(session); }; session.Disconnected += (__, ___) => { Console.WriteLine($"{session.Id}| Disconnected."); Clients.Remove(session); ClientDisconnected?.Invoke(this, session); session.Dispose(); }; Console.WriteLine($"{session.Id}| Connected."); ClientConnected?.Invoke(this, session); session.Start(); } _tcpListener.Stop(); }); }
private void MonitorIncomingConnection() { listener.Start(); while (true) { try { if (Abort) { //Terminating Server and Monitoring Loop listener.Stop(); Trace.WriteLine(Name + ": TCP Server Stopped."); DisconnectAllClients(); return; } if (!listener.Pending()) { Thread.Sleep(10); } else { System.Net.Sockets.TcpClient client = listener.AcceptTcpClient(); Trace.WriteLine(Name + ": New Connection Detected..."); TcpServerConnectEventArgs eArgs = new TcpServerConnectEventArgs() { Client = client }; ClientConnecting?.Invoke(this, eArgs); if (eArgs.Accept) { //Connection Accepted TcpServerConnection newConnection = null; newConnection = new TcpServerConnection(this, client, Certificate); newConnection.MessageDelimiter = MessageDelimiter; Trace.WriteLine(Name + ": Connection Accepted: Client = " + newConnection.ClientIPAddress); newConnection.ClientDisconnected += OnClientDisconnected; lock (ActiveConnections) { ActiveConnections.Add(newConnection); } ClientConnected?.Invoke(this, new TcpServerEventArgs() { Client = newConnection }); } else { //Connection Refused Trace.WriteLine(Name + ": Connection Rejected."); client.Close(); } } } catch (Exception ex) { Trace.WriteLine("[WARNING] " + Name + ": Exception raised from Connection Monitoring Thread!\n" + ex.Message); continue; } } }
async void HandleClientConnection(StreamSocket socket) { var client = new IOTClient(socket); lock (clientList) { var existingClient = clientList.FirstOrDefault(c => c.RemoteAddress.Equals(socket.Information.RemoteAddress)); if (existingClient != null) { existingClient.Dispose(); clientList.Remove(existingClient); } clientList.Add(client); } ClientConnected?.Invoke(this, client); await client.MessageLoop(); lock (clientList) { clientList.Remove(client); client.Dispose(); } }
public void Run(int port) { _listener.ConnectionRequestEvent += request => { request.AcceptIfKey(_clientKey); }; _listener.PeerConnectedEvent += peer => { var param = FuncCreateParamOnConnect(peer); _peers.Add(param); netId2Peer.Add(peer.Id, param); ClientConnected?.Invoke(peer); }; _listener.NetworkReceiveEvent += (peer, reader, method) => { OnDataReceived(peer, reader.GetRemainingBytes()); }; _listener.PeerDisconnectedEvent += (peer, info) => { var param = netId2Peer[peer.Id]; FuncRemoveParamOnDisconnect?.Invoke(peer, param); _peers.Remove(param); netId2Peer.Remove(peer.Id); ClientDisconnected?.Invoke(peer); }; _server.Start(port); }
private async Task Loop() { while (!_tokenSource.IsCancellationRequested) { try { PipeAccessRule rule = new(new SecurityIdentifier(WellKnownSidType.WorldSid, null), PipeAccessRights.FullControl, AccessControlType.Allow); PipeSecurity pipeSecurity = new(); pipeSecurity.SetAccessRule(rule); NamedPipeServerStream pipeStream = NamedPipeServerStreamAcl.Create( _pipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 1024, 0, pipeSecurity); await pipeStream.WaitForConnectionAsync(_tokenSource.Token).ConfigureAwait(false); PipeReader reader = new(pipeStream); reader.CommandReceived += OnReaderCommandReceived; reader.Disconnected += OnReaderDisconnected; _readers.Add(reader); ClientConnected?.Invoke(this, EventArgs.Empty); } catch (Exception e) { Exception?.Invoke(this, e); } } }
private void WebSocketPacketReceived(Packet packet) { lock (syncObject) { switch (packet.Action) { case WebSocketAction.Connect: ClientConnected?.Invoke(packet.RemoteEndPoint, ((ConnectionPacket)packet).Cookies); break; case WebSocketAction.SendText: ClientSendText?.Invoke(packet.RemoteEndPoint, packet.Text); break; case WebSocketAction.Disconnect: var client = webSocketClients.FirstOrDefault(c => c.RemoteEndPoint.Equals(packet.RemoteEndPoint)); if (client != null) { client.Disconnect(4000, "Responding to client's request to close the connection."); webSocketClients.Remove(client); ClientDisconnected?.Invoke(packet.RemoteEndPoint, packet.Text); } break; default: throw new NotImplementedException(); } } }
/// <summary> /// Fires the ClientConnected event. /// </summary> /// <param name="client">Client that connected</param> public void FireClientConnected(Client client) { PluginUtils.ProtectedInvoke(() => { ClientConnected?.Invoke(client); }, "ClientConnected"); }
public override void OnMessageReceived(UdpReceiveResult result) { if (result.Buffer == null) { return; } if (result.Buffer.Length == 0) { return; } var message = MdvrMessageHelper.Parse(result.Buffer); if (message == null) { return; } var client = new DeviceClient(message.DevIDNO, result.RemoteEndPoint.Address, result.RemoteEndPoint.Port); if (Clients.ContainsKey(message.DevIDNO) == true) { client = Clients[message.DevIDNO]; } else { if (Clients.TryAdd(message.DevIDNO, client) == true) { ClientConnected?.Invoke(message.DevIDNO); } } HandleMessage(message, client); }
void HandleClient(TcpClient client) { var tcpClient = client; var stream = tcpClient.GetStream(); ClientConnected?.Invoke(client); var message = new byte[4096]; while (true) { var bytesRead = 0; try { bytesRead = stream.Read(message, 0, 4096); } catch { /* Clause not empty now, is it ReSharper? Haha! */ } // Client disconnected if (bytesRead == 0 || !ServerRunning) { ClientDisconnected?.Invoke(client); break; } var fullMessage = new ASCIIEncoding().GetString(message, 0, bytesRead).Replace("\r", "").Replace("\n", ""); InvokeOnCommandRecieved(fullMessage, tcpClient); } }
private async Task SetupClient(Socket client) { lock (_pending) { _pending.Add(client); } _logger.LogVerbose(Properties.Resources.TcpNetworkListener_ConnectionLogString, _localEndpoint); StreamSocketDataAdapter da = new StreamSocketDataAdapter(client, _localEndpoint.ToString()); ClientConnectedEventArgs e = new ClientConnectedEventArgs(da); NetUtils.PopulateBagFromSocket(client, e.Properties); try { await Task.Run(() => ClientConnected.Invoke(this, e)); } catch { client.Dispose(); } finally { lock (_pending) { _pending.Remove(client); } } }
public void Start() { m_Logger.Log("Starting localhost communication server.", MessageTypeEnum.INFO); IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(LOCALHOST), m_Port); m_Listener = new TcpListener(endPoint); m_Listener.Start(); m_Logger.Log($"Waiting for new connections on port {m_Port}", MessageTypeEnum.INFO); Task task = new Task(() => { while (true) { try { TcpClient client = m_Listener.AcceptTcpClient(); ClientConnectedEventArgs args = new ClientConnectedEventArgs(); args.Client = client; ClientConnected.Invoke(this, args); m_Logger.Log("New connection accepted", MessageTypeEnum.INFO); m_ClientHandler.handleClient(client, m_Controller, m_Logger); m_Logger.Log("QUITING CLIENT", MessageTypeEnum.WARNING); clientDisconnected.Invoke(this, client); } catch (SocketException m_Error) { m_Logger.Log($"Got exception: {m_Error.ToString()}", MessageTypeEnum.INFO); break; } } }); task.Start(); }
private void AcceptCompleted(Socket socket, SocketAsyncEventArgs args) { var clientSocket = args.AcceptSocket; var client = new ConnectedClient(clientSocket); _clients.TryAdd(clientSocket, client); _receiveQueue.TryAdd(clientSocket, new ConcurrentQueue <SocketAsyncEventArgs>()); ClientConnected?.Invoke(client); _acceptArgs.AcceptSocket = null; if (!_listener.AcceptAsync(_acceptArgs)) { SocketOperationCompleted(_listener, _acceptArgs); } var receiveArgs = _receiveArgs.Get(); if (!clientSocket.ReceiveAsync(receiveArgs)) { SocketOperationCompleted(clientSocket, receiveArgs); } ProcessClientMessages(clientSocket); }
public void Register(string sMachineInfo, NebulaModuleInfo[] hModules) { OperationContext hCurrent = OperationContext.Current; INebulaMasterServiceCB hCb = hCurrent.GetCallbackChannel <INebulaMasterServiceCB>(); T hClient; if (m_hClients.TryGetValue(hCb, out hClient)) { hClient.Modules.AddRange(hModules); } else { (hCb as ICommunicationObject).Faulted += OnFaulted; RemoteEndpointMessageProperty hRemoteProperty = (OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty); hClient = new T(); hClient.Id = Interlocked.Increment(ref m_iCounter); hClient.Callback = hCb; hClient.Machine = sMachineInfo; hClient.Address = new IPEndPoint(IPAddress.Parse(hRemoteProperty.Address), hRemoteProperty.Port); hClient.Modules = new List <NebulaModuleInfo>(hModules); m_hClients.TryAdd(hCb, hClient); ClientConnected?.Invoke(hClient); } }
async Task Run(TaskCompletionSource <bool> tcs) { try { listener = new HttpListener(); listener.Prefixes.Add(baseUri); listener.Start(); } catch (Exception ex) { tcs.SetException(ex); } Log.Information($"Http server listening at {baseUri}"); tcs.SetResult(true); // Loop for (; ;) { var c = await listener.GetContextAsync().ConfigureAwait(false); try { ClientConnected?.Invoke(this, null); await ProcessRequest(c).ConfigureAwait(false); } catch (Exception ex) { Log.Exception(ex); } } }
public override async Task WaitForConnectionsAsync(CancellationToken token) { if (iteration % 2 == 0) { if (ClientConnected != null) { ClientConnected.Invoke(this, new IpcServerClientConnectedEventArgs()); } } if (iteration % 3 == 0) { if (ClientDisconnected != null) { ClientDisconnected.Invoke(this, new IpcServerClientDisconnectedEventArgs()); } } if (iteration < IterationCount) { Interlocked.Increment(ref iteration); } else { this.Cancel(); } await Task.CompletedTask; }
/// <summary> /// 添加新客户 /// </summary> /// <param name="e"></param> private void ProcessAccept(SocketAsyncEventArgs e) { if (e.AcceptSocket.RemoteEndPoint == null) { throw new Exception("服务器停止."); } //获取接受的客户端连接的套接字,并将其放入用户令牌中 AsyncUserToken userToken = m_asyncUserTokenPool.Pop(); m_asyncUserTokenList.Add(userToken); userToken.Socket = e.AcceptSocket; userToken.Identifier = userToken.Socket.RemoteEndPoint.ToString(); userToken.ConnectDateTime = DateTime.Now; try { //触发客户端连接事件 ClientConnected?.Invoke(this, userToken); //一旦连接了客户机,就向连接发送一个接收 bool willRaiseEvent = userToken.Socket.ReceiveAsync(userToken.RecvEventArgs); if (!willRaiseEvent) { ProcessReceive(userToken.RecvEventArgs); } } catch (Exception ex) { } //接受下一个连接请求 StartAccept(e); }
void acceptCompleted(Socket accepted) { // Send a ConnectionAccepted. try { ClientRepresentation client = new ClientRepresentation(this) { ClientSocket = accepted }; connectedClients.Add(client); client.MessageReceived += ProcessMessageBytes; client.SendBytes(SocketPipeHelper.BuildMessage(MessageType.ConnectionAccepted, null)); ClientConnected?.Invoke(this); client.AwaitBytes(); } finally { if (!isStopped) { serverAccept(); } } }
private void HandleHello(IPEndPoint endpoint, Message message) { var client = GetClient(endpoint); if (client != null) { Debug($"Client with endpoint {endpoint.Address}:{endpoint.Port} already on list ({client.Nickname})."); return; } var nickname = message.GetTextContent(); using (var database = new RozmawiatorDb()) { var user = database.Users.FirstOrDefault(u => u.UserName == nickname); if (user == null) { Debug($"Client {nickname} with endpoint {endpoint.Address}:{endpoint.Port} does not exist in database."); return; } } var newClient = AddClient(endpoint, nickname); Send(newClient, Message.Hello(Configuration.Host.Name)); Debug($"{nickname} connected ({endpoint.Address}:{endpoint.Port})"); ClientConnected?.Invoke(newClient); }
private void OnClientConnected(object sender, MqttClientConnectedEventArgs eventArgs) { MqttTrace.Information(nameof(MqttServer), $"Client '{eventArgs.Identifier}': Connected."); ClientConnected?.Invoke(this, eventArgs); Task.Run(() => _clientSessionsManager.RunClientSessionAsync(eventArgs), _cancellationTokenSource.Token); }
/// <summary> /// Waits for new events from another thread and then processes the event queue when messages /// are available. This serves to run all message events on a single thread instead of the multiple threads /// that ASP.NET uses for handling requests. /// </summary> private void ProcessNetworkEvents() { while (true) { // Wait until a new message is received. eventTrigger.WaitOne(); // Dequeue all received messages and execute the appropriate event. while (!eventQueue.IsEmpty) { if (eventQueue.TryDequeue(out var item)) { switch (item.Type) { case IncomingMessageType.Connect: ClientConnected?.Invoke(item.Connection); break; case IncomingMessageType.Disconnect: ClientDisconnected?.Invoke(item.Connection); break; case IncomingMessageType.Data: MessageReceived?.Invoke(item.Connection, item.Message); break; default: throw new ArgumentOutOfRangeException(); } } } } }