private void _listener_ConnectionReceived(object sender, Sockets.Plugin.Abstractions.TcpSocketListenerConnectEventArgs e) { TcpSocketClient client = (TcpSocketClient)e.SocketClient; Socket ns = new Socket(client); OnNewConnection?.Invoke(ns); }
/// <summary> /// Initialize the endpoint listeners for the web socket /// </summary> private void InitEndpoints() { _conferenceHubProxy.On <string>("newConnection", (peerId) => { OnNewConnection?.Invoke(this, new PeerConnectionEventArgs { PeerId = peerId }); }); _conferenceHubProxy.On <string, string>("receiveOfferAnswer", (peerId, json) => { OnNewOfferAnswer?.Invoke(this, new OfferAnswerEventArgs { PeerId = peerId, Json = json }); }); _conferenceHubProxy.On <string, string>("receiveCandidate", (peerId, json) => { OnNewCandidate?.Invoke(this, new CandidateEventArgs { PeerId = peerId, Json = json }); }); }
protected internal void SendNewConnection(DateTime ServerTimestamp, IPSocket RemoteSocket, String ConnectionId, TCPConnection TCPConnection) { OnNewConnection?.Invoke(this, ServerTimestamp, RemoteSocket, ConnectionId, TCPConnection); }
protected void SendNewConnection(TCPServer TCPServer, DateTime Timestamp, IPSocket RemoteSocket, String ConnectionId, TCPConnection TCPConnection) { OnNewConnection?.Invoke(TCPServer, Timestamp, RemoteSocket, ConnectionId, TCPConnection); }
public void Poll() { if (!IsListening) { _udpListenTask = null; } lock (_newConnectionQueue) { while (_newConnectionQueue.Count > 0) { int connectionId = _newConnectionQueue.Dequeue(); string username = _usernamesQueue.Dequeue(); OnNewConnection?.Invoke(connectionId, username); } } lock (_reconnectQueue) { while (_reconnectQueue.Count > 0) { int connectionId = _reconnectQueue.Dequeue(); OnReconnect?.Invoke(connectionId); } } lock (_disconnectQueue) { while (_disconnectQueue.Count > 0) { int connectionId = _disconnectQueue.Dequeue(); OnDisconnect?.Invoke(connectionId); } } lock (_receiveIdQueue) { while (_receiveIdQueue.Count > 0) { int connectionId = _receiveIdQueue.Dequeue(); if (_receiveDataQueue.Count > 0) { byte[] data = _receiveDataQueue.Dequeue(); OnDataReceived?.Invoke(connectionId, data); } else { LogManager.RuntimeLogger.LogError("Network error! Data queue is empty!"); } } } }
void ProcessNetworkEvent(NetworkEvent e) { switch (e.Type) { case NetEventType.ServerInitialized: OnServerStartSuccess?.Invoke(e); break; case NetEventType.ServerInitFailed: OnServerStartFailure?.Invoke(e); break; // Received after network.StopServer case NetEventType.ServerClosed: OnServerStopped?.Invoke(e); break; case NetEventType.NewConnection: OnNewConnection?.Invoke(e); break; case NetEventType.ConnectionFailed: OnConnectionFailed?.Invoke(e); break; case NetEventType.Disconnected: OnDisconnection?.Invoke(e); break; case NetEventType.ReliableMessageReceived: OnMessageReceived?.Invoke(e, true); break; case NetEventType.UnreliableMessageReceived: OnMessageReceived?.Invoke(e, false); break; } }
/// <summary> /// Initialize the TCP server using the given parameters. /// </summary> /// <param name="IIPAddress">The listening IP address(es)</param> /// <param name="Port">The listening port</param> /// <param name="ServiceBanner">Service banner.</param> /// <param name="ServerThreadName">The optional name of the TCP server thread.</param> /// <param name="ServerThreadPriority">The optional priority of the TCP server thread.</param> /// <param name="ServerThreadIsBackground">Whether the TCP server thread is a background thread or not.</param> /// <param name="ConnectionIdBuilder">An optional delegate to build a connection identification based on IP socket information.</param> /// <param name="ConnectionThreadsNameBuilder">An optional delegate to set the name of the TCP connection threads.</param> /// <param name="ConnectionThreadsPriorityBuilder">An optional delegate to set the priority of the TCP connection threads.</param> /// <param name="ConnectionThreadsAreBackground">Whether the TCP connection threads are background threads or not (default: yes).</param> /// <param name="ConnectionTimeout">The TCP client timeout for all incoming client connections in seconds (default: 30 sec).</param> /// <param name="MaxClientConnections">The maximum number of concurrent TCP client connections (default: 4096).</param> /// <param name="Autostart">Start the TCP server thread immediately (default: no).</param> public TCPServer(IIPAddress IIPAddress, IPPort Port, String ServiceBanner = __DefaultServiceBanner, String ServerThreadName = null, ThreadPriority ServerThreadPriority = ThreadPriority.AboveNormal, Boolean ServerThreadIsBackground = true, ConnectionIdBuilder ConnectionIdBuilder = null, ConnectionThreadsNameBuilder ConnectionThreadsNameBuilder = null, ConnectionThreadsPriorityBuilder ConnectionThreadsPriorityBuilder = null, Boolean ConnectionThreadsAreBackground = true, TimeSpan?ConnectionTimeout = null, UInt32 MaxClientConnections = __DefaultMaxClientConnections, Boolean Autostart = false) { #region TCP Socket this._IPAddress = IIPAddress; this._Port = Port; this._IPSocket = new IPSocket(_IPAddress, _Port); this._TCPListener = new TcpListener(new System.Net.IPAddress(_IPAddress.GetBytes()), _Port.ToInt32()); #endregion #region TCP Server this._ServiceBanner = (ServiceBanner.IsNotNullOrEmpty()) ? ServiceBanner : __DefaultServiceBanner; this.ServerThreadName = (ServerThreadName != null) ? ServerThreadName : __DefaultServerThreadName + this.IPSocket.ToString(); this.ServerThreadPriority = ServerThreadPriority; this.ServerThreadIsBackground = ServerThreadIsBackground; #endregion #region TCP Connections this._TCPConnections = new ConcurrentDictionary <IPSocket, TCPConnection>(); this.ConnectionIdBuilder = (ConnectionIdBuilder != null) ? ConnectionIdBuilder : (Sender, Timestamp, LocalSocket, RemoteIPSocket) => "TCP:" + RemoteIPSocket.IPAddress + ":" + RemoteIPSocket.Port; this.ConnectionThreadsNameBuilder = (ConnectionThreadsNameBuilder != null) ? ConnectionThreadsNameBuilder : (Sender, Timestamp, LocalSocket, RemoteIPSocket) => "TCP thread " + RemoteIPSocket.IPAddress + ":" + RemoteIPSocket.Port; this.ConnectionThreadsPriorityBuilder = (ConnectionThreadsPriorityBuilder != null) ? ConnectionThreadsPriorityBuilder : (Sender, Timestamp, LocalSocket, RemoteIPSocket) => ThreadPriority.AboveNormal; this.ConnectionThreadsAreBackground = ConnectionThreadsAreBackground; this._ConnectionTimeout = ConnectionTimeout.HasValue ? ConnectionTimeout.Value : TimeSpan.FromSeconds(30); this._MaxClientConnections = MaxClientConnections; #endregion #region TCP Listener Thread this.CancellationTokenSource = new CancellationTokenSource(); this.CancellationToken = CancellationTokenSource.Token; _ListenerThread = new Thread(() => { #if __MonoCS__ // Code for Mono C# compiler #else Thread.CurrentThread.Name = this.ServerThreadName; Thread.CurrentThread.Priority = this.ServerThreadPriority; Thread.CurrentThread.IsBackground = this.ServerThreadIsBackground; #endif #region SetSocketOptions // IOControlCode.* // fd.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, tcpKeepalive); // bytes.PutInteger(endian, tcpKeepalive, 0); // bytes.PutInteger(endian, tcpKeepaliveIdle, 4); // bytes.PutInteger(endian, tcpKeepaliveIntvl, 8); // fd.IOControl(IOControlCode.KeepAliveValues, (byte[])bytes, null); #endregion try { _IsRunning = true; while (!_StopRequested) { // Wait for a new/pending client connection while (!_StopRequested && !_TCPListener.Pending()) { Thread.Sleep(5); } // Break when a server stop was requested if (_StopRequested) { break; } // Processing the pending client connection within its own task var NewTCPClient = _TCPListener.AcceptTcpClient(); // var NewTCPConnection = _TCPListener.AcceptTcpClientAsync(). // ContinueWith(a => new TCPConnection(this, a.Result)); // // ConfigureAwait(false); // Store the new connection //_SocketConnections.AddOrUpdate(_TCPConnection.Value.RemoteSocket, // _TCPConnection.Value, // (RemoteEndPoint, TCPConnection) => TCPConnection); Task.Factory.StartNew(Tuple => { try { var _Tuple = Tuple as Tuple <TCPServer, TcpClient>; var NewTCPConnection = new ThreadLocal <TCPConnection>( () => new TCPConnection(_Tuple.Item1, _Tuple.Item2) ); #region Copy ExceptionOccured event handlers //foreach (var ExceptionOccuredHandler in MyEventStorage) // _TCPConnection.Value.OnExceptionOccured += ExceptionOccuredHandler; #endregion #region OnNewConnection // If this event closes the TCP connection the OnNotification event will never be fired! // Therefore you can use this event for filtering connection initiation requests. OnNewConnection?.Invoke(NewTCPConnection.Value.TCPServer, NewTCPConnection.Value.ServerTimestamp, NewTCPConnection.Value.RemoteSocket, NewTCPConnection.Value.ConnectionId, NewTCPConnection.Value); if (!NewTCPConnection.Value.IsClosed) { OnNotification?.Invoke(NewTCPConnection.Value); } #endregion } catch (Exception e) { while (e.InnerException != null) { e = e.InnerException; } OnExceptionOccured?.Invoke(this, DateTime.Now, e); Console.WriteLine(DateTime.Now + " " + e.Message + Environment.NewLine + e.StackTrace); } }, new Tuple <TCPServer, TcpClient>(this, NewTCPClient)); } #region Shutdown // Request all client connections to finish! foreach (var _SocketConnection in _TCPConnections) { _SocketConnection.Value.StopRequested = true; } // After stopping the TCPListener wait for // all client connections to finish! while (_TCPConnections.Count > 0) { Thread.Sleep(5); } #endregion } #region Exception handling catch (Exception Exception) { var OnExceptionLocal = OnExceptionOccured; if (OnExceptionLocal != null) { OnExceptionLocal(this, DateTime.Now, Exception); } } #endregion _IsRunning = false; }); #endregion if (Autostart) { Start(); } }
public override void Update(GameTime gameTime) { WasConnected = IsConnected; if (Started) { if (IsServer) { NetIncomingMessage _msg; while ((_msg = _Server.ReadMessage()) != null) { switch (_msg.MessageType) { case NetIncomingMessageType.Data: var _incMsg = ReadMessage(_msg); OnGotMessage?.Invoke(_incMsg); break; case NetIncomingMessageType.VerboseDebugMessage: case NetIncomingMessageType.DebugMessage: case NetIncomingMessageType.WarningMessage: case NetIncomingMessageType.ErrorMessage: Console.WriteLine(_msg.ReadString()); break; default: Console.WriteLine("Unhandled type: " + _msg.MessageType); break; } _Server.Recycle(_msg); } } else { NetIncomingMessage _msg; while ((_msg = _Client.ReadMessage()) != null) { switch (_msg.MessageType) { case NetIncomingMessageType.Data: var _incMsg = ReadMessage(_msg); OnGotMessage?.Invoke(_incMsg); break; case NetIncomingMessageType.VerboseDebugMessage: case NetIncomingMessageType.DebugMessage: case NetIncomingMessageType.WarningMessage: case NetIncomingMessageType.ErrorMessage: Console.WriteLine(_msg.ReadString()); break; default: Console.WriteLine("Unhandled type: " + _msg.MessageType); break; } _Client.Recycle(_msg); } } } if (IsConnected && !WasConnected) { OnNewConnection?.Invoke(); } if (!IsConnected && WasConnected) { OnLostConnection?.Invoke(); } }
protected void RaiseNewConnectionHandler(AbstractConnection client) { OnNewConnection?.Invoke(client); }
internal override void AddNewConnection(FSWPage page) { base.AddNewConnection(page); OnNewConnection?.Invoke((T)page); }