public Host(int port) { EnableHandshake = true; AllowedTokens = AllowedTokens.Any; //ValidateMessageTypes(); _listenThread = new Thread(() => Listen(port)); _port = port; _isListening = false; _connectionManager = new ConnectionManager(); _receiveHandlers = new Dictionary <short, IList <ReceiveHandler> >(); Rnd = new Random(); AddHandler((short)MessageType.Token, (m, c) => { _hostToken = m.ConnectionToken; if (OnConnect != null) { OnConnect.Invoke(); } }); AddHandler((short)MessageType.Handshake, (m, c) => { if (!EnableHandshake) { return; } if (ConnectionCreated != null) { ConnectionCreated.Invoke(c); } SendToken(c); }); AddHandler((short)MessageType.Ack, (m, c) => { c.ProcessAck(m); }); ServerTimer.OnTick += ServerTick; }
public Host(int port) { EnableHandshake = true; AllowedTokens = AllowedTokens.Any; //ValidateMessageTypes(); _listenThread = new Thread(() => Listen(port)); _isListening = false; _connectionManager = new ConnectionManager(); _receiveHandlers = new Dictionary <short, IList <ReceiveHandler> >(); AddHandler((short)MessageType.Token, (m, c) => { _hostToken = m.ConnectionToken; if (OnConnect != null) { OnConnect.Invoke(); } }); AddHandler((short)MessageType.Handshake, (m, c) => { if (!EnableHandshake) { return; } if (ConnectionCreated != null) { ConnectionCreated.Invoke(c); } SendToken(c); }); AddHandler((short)MessageType.Ack, (m, c) => { c.ProcessAck(m); }); ServerTimer.OnTick += ServerTick; AddHandler((short)MessageType.Resend, (m, c) => { var mode = (m.Ordered ? Mode.Ordered : Mode.None) & (m.Reliable ? Mode.Reliable : Mode.None) & (m.Sequenced ? Mode.Sequenced : Mode.None); var message = new Message((short)MessageType.SendToEndPoint, mode, m.Body); foreach (var connection in GetConnections()) { if (c != connection) { Send(message, connection); } } }); AddHandler((short)MessageType.SendToEndPoint, (m, c) => { var ds = DataStorage.CreateForRead(m.Body); var methodName = ds.ReadString(); NetworkController.Instance.RPCMessage(methodName, ds); }); }
public IDbConnection CreateConnection() { if (_sharedConnection != null) { return(_sharedConnection); } var connection = _connectionModifier(_connectionProvider.CreateConnection()); var args = ConnectionCreated.Raise(this, () => new ConnectionCreatedEventArgs(connection)); if (args != null && args.OverriddenConnection != null) { return(args.OverriddenConnection); } return(connection); }
void DoAcceptTcpClientCallback(IAsyncResult ar) { if (!ar.IsCompleted) { return; } bool docontinue = true; var listener = (Socket)ar.AsyncState; try { var socket = listener.EndAccept(ar); var ntcpc = new NTCPClientIncoming(socket); Logging.LogTransport($"NTCPHost: incoming connection {ntcpc.DebugId} from " + $"{socket.RemoteEndPoint} created."); ConnectionCreated?.Invoke(ntcpc); ntcpc.Connect(); lock ( Clients ) { Clients.Add(ntcpc); } } catch (ObjectDisposedException) { docontinue = false; } catch (Exception ex) { Logging.Log(ex); } try { if (docontinue) { listener.BeginAccept(new AsyncCallback(DoAcceptTcpClientCallback), listener); } } catch (Exception ex) { Logging.Log(ex); } }
protected virtual void OnConnectionCreated(ConnectionCreatedEventArgs e) { ConnectionCreated?.Invoke(this, e); }
protected virtual void OnConnectionCreated(PBSConnection connection) { _connections = null; ConnectionCreated?.Invoke(connection); }
private void ReceiveCallback(IAsyncResult ar) { SSUSession session = null; try { EndPoint ep = RemoteEP; var size = MySocket.EndReceiveFrom(ar, ref ep); if (ep.AddressFamily != AddressFamily.InterNetwork && (!SessionLayer.RouterContext.Inst.UseIpV6 || ep.AddressFamily != AddressFamily.InterNetworkV6)) { return; // TODO: Add IPV6 } if (size <= 37) { Logging.LogDebugData($"SSU Recv: {size} bytes [0x{size:X}] from {ep} (hole punch, ignored)"); return; } var sessionendpoint = (IPEndPoint)ep; Logging.LogDebugData($"SSU Recv: {size} bytes [0x{size:X}] from {ep}"); lock ( Sessions ) { if (!Sessions.ContainsKey(sessionendpoint)) { if (IPFilter.IsFiltered(((IPEndPoint)ep).Address)) { Logging.LogTransport($"SSUHost ReceiveCallback: IPAddress {sessionendpoint} is blocked. {size} bytes."); return; } ++IncommingConnectionAttempts; Logging.LogTransport($"SSUHost: incoming connection " + $"from {sessionendpoint} created."); session = new SSUSession( this, Send, (IPEndPoint)ep, MyRouterContext); Sessions[sessionendpoint] = session; Logging.LogTransport($"SSUHost: incoming connection " + $"{session.DebugId} from {sessionendpoint} created."); NeedCpu(session); ConnectionCreated?.Invoke(session); } else { session = Sessions[sessionendpoint]; } } var localbuffer = BufRefLen.Clone(ReceiveBuf, 0, size); #if DEBUG Stopwatch Stopwatch1 = new Stopwatch(); Stopwatch1.Start(); #endif try { session.Receive(localbuffer); } catch (ThreadAbortException taex) { AddFailedSession(session); Logging.Log(taex); } catch (ThreadInterruptedException tiex) { AddFailedSession(session); Logging.Log(tiex); } catch (ChecksumFailureException cfex) { AddFailedSession(session); Logging.Log(cfex); } catch (SignatureCheckFailureException scex) { AddFailedSession(session); Logging.Log(scex); } catch (FailedToConnectException fcex) { AddFailedSession(session); #if LOG_MUCH_TRANSPORT Logging.LogTransport(fcex); #endif if (session != null) { NetDb.Inst.Statistics.FailedToConnect(session.RemoteRouterIdentity.IdentHash); session.RaiseException(fcex); } } #if DEBUG Stopwatch1.Stop(); if (Stopwatch1.ElapsedMilliseconds > SessionCallWarningLevelMilliseconds) { Logging.LogTransport( $"SSUHost ReceiveCallback: WARNING Session {session} used {Stopwatch1.ElapsedMilliseconds}ms cpu."); } #endif } catch (Exception ex) { AddFailedSession(session); Logging.Log(ex); if (session != null && session.RemoteRouterIdentity != null && NetDb.Inst != null) { NetDb.Inst.Statistics.DestinationInformationFaulty(session.RemoteRouterIdentity.IdentHash); session.RaiseException(ex); } } finally { RemoteEP = LocalEP; MySocket.BeginReceiveFrom(ReceiveBuf, 0, ReceiveBuf.Length, SocketFlags.None, ref RemoteEP, new AsyncCallback(ReceiveCallback), MySocket); } }
protected virtual void OnConnectionCreated(object sender, EventArgs e) { ConnectionCreated?.Invoke(sender, e); }
public void OnConnectionCreated() { ConnectionCreated?.Invoke(this, new ConnectionCreatedEventArgs { }); }
internal virtual void OnConnectionCreated(RemotingDbConnection connection) { ConnectionCreated?.Invoke(connection); }
private void ReceiveCallback(IAsyncResult asyncResult) { var state = asyncResult.AsyncState as BeginReceiveState; if (state == null) { return; } int bytesRecieved = 0; if (state.ListenSocket != null) { lock (_socketAccessLock) { if (state.ListenSocket != null) { try { bytesRecieved = state.ListenSocket.EndReceiveFrom(asyncResult, ref state.RemotePeer); var bufferSize = state.ListenSocket.BeginReceiveFrom(state.Data, 0, state.Data.Length, SocketFlags.None, ref state.RemotePeer, ReceiveCallback, state); } catch (ObjectDisposedException) // Socket has been closed. { if (_clientsTable.Contains(state.RemotePeer)) { _clientsTable.Remove(state.RemotePeer); var ipAddress = ((IPEndPoint)state.RemotePeer).Address; CheckIfAddressIsMapped(ref ipAddress); ConnectionClosed?.Invoke(ipAddress.ToString(), (ushort)((IPEndPoint)state.RemotePeer).Port); } return; } catch (SocketException ex) // An error occurred when attempting to access the socket. { ex.Message._DLOG(); CloseSocket(); return; } catch (InvalidCastException ex) { ex.Message._DLOG(); } } } } if (bytesRecieved > 0) { var ipAddress = ((IPEndPoint)state.RemotePeer).Address; CheckIfAddressIsMapped(ref ipAddress); if (!_clientsTable.Contains(state.RemotePeer)) { _clientsTable.Add(state.RemotePeer); ConnectionCreated?.Invoke(ipAddress.ToString(), (ushort)((IPEndPoint)state.RemotePeer).Port); } // Compose callback data. var receivedData = new ReceivedDataArgs { SourceName = ipAddress.ToString(), ListenerPort = PortNumber }; receivedData.Data = new byte[bytesRecieved]; Array.Copy(state.Data, receivedData.Data, bytesRecieved); DataReceived?.Invoke(receivedData); if (!SuppressDebugOutput) { "Listener accepted {0} << {1}"._DLOG(receivedData.SourceName, Tools.GetHex(receivedData.Data)); } } }