コード例 #1
0
        // Runs in the scheduler thread.
        // Doesn't throw. In case of error both `connection` and `reader` are set to null.
        // Otherwise both are non-null.
        void NewConnection(out IConnection <In, Out> connection, out Reader <In> reader)
        {
            connection = null;
            var r = new Reader <In>();

            try
            {
                connection = _connector.NewConnection();
                Condition.Requires(connection).IsNotNull();
                connection.OnMessage += (TimestampedMsg <In> msg) => r.Push(msg);
                connection.Connect();
                OnConnection?.Invoke(r, new SimpleWriter <In, Out>(connection));
                // If OnConnection() handler swallowed read error exceptions, CheckHealth() will throw.
                r.CheckHealth();
                reader = r;
            }
            catch (Exception e)
            {
                _log.Warn(e, "Unable to connect. Will retry.");
                if (connection != null)
                {
                    try { connection.Dispose(); }
                    catch (Exception ex) { _log.Error(ex, "Ignoring exception from IConnection.Dispose()"); }
                    connection = null;
                }
                reader = null;
            }
        }
コード例 #2
0
 private void HandleConnection(Connection connection)
 {
     ThreadPool.QueueUserWorkItem(delegate
     {
         OnConnection?.Invoke(this, connection);
     });
 }
コード例 #3
0
        private void Listen()
        {
            int i = 0;

            try
            {
                for (i = 0; i <= MaxConnection; ++i)
                {
                    clientSocket.Add(Accept());
                    OnConnection.BeginInvoke(clientSocket[i].RemoteEndPoint.ToString(), null, null);
                    clientSocket[i].Blocking          = true;
                    clientSocket[i].SendBufferSize    = _SendBufferSize;
                    clientSocket[i].ReceiveBufferSize = _ReceiveBufferSize;

                    Thread t = new Thread(Received);
                    t.IsBackground = true;
                    t.Name         = i.ToString();
                    t.Priority     = ThreadPriority.Lowest;
                    t.Start();
                }
            }
            catch
            {
                Error_Message = "服务器已停止";
                OnError.BeginInvoke(Error_Message, null, null);
                CloseSocket(i);
            }
        }
コード例 #4
0
ファイル: ServModule.cs プロジェクト: gonznak/Socket
        private void AcceptClient_ClientDisconnected(OnConnection clientConnection)
        {
            BaseProtocol ci = (BaseProtocol)clientConnection;

            ci.ClientClosed -= AcceptClient_ClientDisconnected;
            Clients.Remove(ci);
        }
コード例 #5
0
    private void FinishConnection()
    {
        ConnectedBlocks.ForEach(block => block.IsConnected = false);

        if (ConnectedBlocks.Count >= 3)
        {
            if (OnConnection != null)
            {
                OnConnection.Invoke(ConnectedBlocks.Count);
            }

            Board.RemoveBlocks(ConnectedBlocks);
            Board.RefreshBlocks();
        }
        if (ConnectedBlocks.Count >= 4)
        {
            FindObjectOfType <GameManager>().RemainingTime++;
        }
        if (ConnectedBlocks.Count >= 5)
        {
            FindObjectOfType <GameManager>().RemainingTime += 3;
        }

        ConnectedBlocks.Clear();

        CurrentColor = null;
        RefreshConnector();
    }
コード例 #6
0
        [ConditionalShow, SerializeField] private bool useless; //在没有数据的时候让标题正常显示
#endif

        private void Awake()
        {
            NetworkSystem.OnUDPReceive    += val => OnUDPReceive?.Invoke(val.message);
            NetworkSystem.OnReceive       += val => OnReceive?.Invoke(val);
            NetworkSystem.OnConnection    += () => OnConnection?.Invoke();
            NetworkSystem.OnDisconnection += () => OnDisconnection?.Invoke();
        }
コード例 #7
0
        private static void AcceptClient_ClientDisconnected(OnConnection clientConnection)
        {
            FTPModule ci = (FTPModule)clientConnection;

            ci.ClientClosed -= AcceptClient_ClientDisconnected;
            Program.Clients.Remove(ci);
        }
コード例 #8
0
        protected override void FireConnection(Tcp.Connection connection, RequestHead req, string subprotocol, byte[] trail)
        {
            Connection newConnection = new Connection(connection, req, new Definition.Connection.ServerMode());

            newConnection.SetSubprotocol(subprotocol);
            OnConnection?.Invoke(newConnection);
            newConnection.Initiate(trail);
        }
コード例 #9
0
 public IModel Connect(CancellationToken cancellationToken, OnConnection onConnection)
 {
     this.cancellationToken = cancellationToken;
     this.currentConnection = this.GetConnection();
     this.currentChannel    = this.currentConnection.CreateModel();
     onConnection?.Invoke(this.currentChannel, this.connectionOptions);
     this.isConsumingAlive = true;
     return(this.currentChannel);
 }
コード例 #10
0
 private void SetDisconnected(string message = "Disconnected.")
 {
     _connectionStatus = message;
     CloudFileWatcher.Access.SetAuthorization(null);
     UserID          = "";
     _settings.Token = null;
     OnConnection?.Invoke(this, new OnConnectionEvent {
         IsSuccess = false
     });
 }
コード例 #11
0
        private void ProcessClient(TcpClient client)
        {
            ClientConnection clientConnection = new ClientConnection(client, SERVER_IP, PORT_NO);

            Console.WriteLine(String.Format("New connection: {0}", client.Client.RemoteEndPoint));
            ConnectionArgs args = new ConnectionArgs(clientConnection);

            OnConnection?.Invoke(this, args);
            ListenToClient(clientConnection);
        }
コード例 #12
0
 /// <summary>
 /// Sets a token for the current session.
 /// </summary>
 /// <param name="token"></param>
 private void SetConnected(Token token)
 {
     _connectionStatus = "Connected.";
     CloudFileWatcher.Access.SetAuthorization(token);
     UserID          = token.user_id;
     _settings.Token = token;
     OnConnection?.Invoke(this, new OnConnectionEvent {
         IsSuccess = true
     });
 }
コード例 #13
0
ファイル: TcpServer.cs プロジェクト: darcymiranda/PFire
        private async Task Accept()
        {
            while (_running)
            {
                var tcpClient = await _listener.AcceptTcpClientAsync().ConfigureAwait(false);

                var newXFireClient = new XFireClient(tcpClient, _clientManager, _logger, OnReceive, OnDisconnection);

                OnConnection?.Invoke(newXFireClient);
            }
        }
コード例 #14
0
ファイル: HttpServer.cs プロジェクト: sps014/HTTP-Server
        private async void HandleClient()
        {
            while (listener.IsListening)
            {
                var context = await listener.GetContextAsync();

                if (listener.IsListening)
                {
                    OnConnection?.Invoke(this, context);
                }
            }
        }
コード例 #15
0
        private void ClientHandler(TcpClient client)
        {
            ConnectionEventArgs connectionEvent = new ConnectionEventArgs(client);

            if (connectionEvent.Request.URL == null)
            {
                connectionEvent.Response.Close();
                return;
            }

            OnConnection?.Invoke(this, connectionEvent);
        }
コード例 #16
0
        protected SocketManager()
        {
            Namespaces = new Dictionary <string, Namespace>();
            var defaultNsp = new Namespace("/");

            Default = defaultNsp;
            lock (Namespaces)
            {
                Namespaces.Add("/", defaultNsp);
            }

            defaultNsp.OnConnection += socket => { OnConnection?.Invoke((T)socket); };
        }
コード例 #17
0
        private void SetConnectionState(ConnectionState newState)
        {
            var oldState = _connectionState;

            _connectionState = newState;

            if (oldState == newState)
            {
                return;
            }

            Connected = newState == ConnectionState.Connected;
            OnConnection?.Invoke(_connectionState);
        }
コード例 #18
0
        public ServerConnection(CreateConnection creator)
        {
            _thread = new Thread(() =>
            {
                while (true)
                {
                    IConnection connection = creator();

                    OnConnection?.Invoke(this, new ConnectionEventArgs {
                        Socket = connection
                    });
                }
            });
            _thread.Start();
        }
コード例 #19
0
ファイル: Namespace.cs プロジェクト: zhshize/BridgeSocket
 public void AddSocket(ISocket socket)
 {
     socket.OnDisconnect += (status, reason) =>
     {
         lock (Sockets)
         {
             Sockets?.Remove(socket);
         }
     };
     lock (Sockets)
     {
         Sockets.Add(socket);
     }
     OnConnection?.Invoke(socket);
 }
コード例 #20
0
        private async Task Accept()
        {
            while (_running)
            {
                Context session = new Context(await _listener.AcceptTcpClientAsync().ConfigureAwait(false));
                Debug.WriteLine("Client connected {0} and assigned session id {1}", session.TcpClient.Client.RemoteEndPoint, session.SessionId);

                OnConnection?.Invoke(session);

#pragma warning disable 4014
                // Fire and forget. Can't be bothered to fix right now. This whole class needs to be rewritten and decoupled
                Receive(session);
#pragma warning restore 4014
            }
        }
コード例 #21
0
ファイル: TcpClient.cs プロジェクト: Tanya5091/UnityClient
        private void ConnectToServer(IPEndPoint endpoint)
        {
            try
            {
                client = new System.Net.Sockets.TcpClient();
                client.Connect(endpoint);
            }
            catch (Exception e)
            {
                Debug.Log(e.Message);
            }

            OnConnection?.Invoke();
            ReadServerMessage();
        }
コード例 #22
0
        //Pause connections. Used by aTello when app paused.
        public void ConnectionSetPause(bool pause)
        {
            //NOTE only pause if connected and only un-pause (connect) when paused.
            if (pause && _connectionState == ConnectionState.Connected)
            {
                SetConnectionState(ConnectionState.Paused);
            }
            else if (pause == false && _connectionState == ConnectionState.Paused)
            {
                //NOTE:send un-pause and not connection event
                OnConnection?.Invoke(ConnectionState.UnPausing);

                _connectionState = ConnectionState.Connected;
            }
        }
コード例 #23
0
        internal void InitGamePadHandlers()
        {
            _gamePadHandlers = new GamePadHandler[MaxGamePads];
            for (int i = 0; i < MaxGamePads; i++)
            {
                var handle = _gamePadHandlers[i] = new GamePadHandler(i);

                // Redirect Events.
                handle.OnConnection += () => OnConnection?.Invoke(handle);
                handle.OnDisconnect += () => OnDisconnected?.Invoke(handle);

                handle.OnButtonDown     += (button, value) => OnButtonDown?.Invoke(handle, button, value);
                handle.OnButtonUp       += (button, value) => OnButtonUp?.Invoke(handle, button, value);
                handle.OnButtonPressed  += (button, value) => OnButtonPressed?.Invoke(handle, button, value);
                handle.OnButtonClicked  += (button, value) => OnButtonClicked?.Invoke(handle, button, value);
                handle.OnButtonReleased += (button, value) => OnButtonReleased?.Invoke(handle, button, value);
            }
        }
コード例 #24
0
        /// <summary>
        /// Handle a HTTP Upgrade request.
        /// </summary>
        /// <param name="req"></param>
        /// <param name="conn"></param>
        public void HandleUpgrade(HttpServerRequest req, TcpSocket socket, ArraySegment <byte> head)
        {
            if (!socket.Readable || !socket.Writable)
            {
                socket.Destroy();
                return;
            }

            if (OnConnection == null)
            {
                AbortConnection(socket, 400);
                return;
            }

            var upgrade = req.Headers["upgrade"];
            var version = req.Headers["sec-websocket-version"];

            if ((version != "13" && version != "8") ||
                !string.Equals(upgrade, "websocket", StringComparison.InvariantCultureIgnoreCase))
            {
                socket.Write(Encoding.ASCII.GetBytes(
                                 "HTTP/1.1 400 Bad Request\r\n" +
                                 "Connection: close\r\n" +
                                 "Sec-WebSocket-Version: 13, 8\r\n"));
                socket.Close();
                return;
            }

            string acceptKey;

            using (var sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider()) {
                var key = req.Headers["sec-websocket-key"];
                acceptKey = Convert.ToBase64String(sha1.ComputeHash(Encoding.ASCII.GetBytes(key + GUID)));
            }

            socket.Write(Encoding.UTF8.GetBytes(
                             "HTTP/1.1 101 Switching Protocols\r\n" +
                             "Upgrade: websocket\r\n" +
                             "Connection: Upgrade\r\n" +
                             "Sec-WebSocket-Accept: " + acceptKey + "\r\n\r\n"));
            socket.Flush();

            OnConnection.Invoke(new WebSocket(socket, req, head));
        }
コード例 #25
0
        public bool TryConnect()
        {
            _logger.LogInformation("RabbitMQ Client is trying to connect");

            if (IsConnected)
            {
                return(true);
            }

            lock (sync_root)
            {
                var policy = RetryPolicy.Handle <SocketException>()
                             .Or <BrokerUnreachableException>()
                             .WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) =>
                {
                    _logger.LogWarning($"RabbitMQ Client could not connect after {time.TotalSeconds:n1}s ({ex.Message})");
                }
                                           );

                policy.Execute(() =>
                {
                    _connection = _connectionFactory
                                  .CreateConnection();
                });

                if (IsConnected)
                {
                    _connection.ConnectionShutdown += OnConnectionShutdown;
                    _connection.CallbackException  += OnCallbackException;
                    _connection.ConnectionBlocked  += OnConnectionBlocked;

                    OnConnection?.Invoke(this, _connection);
                    return(true);
                }
                else
                {
                    _logger.LogCritical("FATAL ERROR: RabbitMQ connections could not be created and opened");
                    LoopTryConnect();
                    return(false);
                }
            }
        }
コード例 #26
0
    private void FinishConnection()
    {
        _connectedBlocks
        .ForEach(block => block.isConnected = false);

        if (_connectedBlocks.Count >= 3)
        {
            if (OnConnection != null)
            {
                OnConnection.Invoke(_connectedBlocks.Count);
            }

            _board.RemoveConnectedBlocks(_connectedBlocks);
            _board.RefreshBlocks();
        }

        _connectedBlocks.Clear();
        _currentColor = null;
        RefreshConnection();
    }
コード例 #27
0
    /// <summary>
    /// funkcja wyświetlana w momencie, gdy użytkownik przestawał dotykać ekran
    /// </summary>
    private void FinishConnection()
    {
        ConnectedBlocks
        .ForEach(block => block.IsConnected = false);

        if (ConnectedBlocks.Count >= 3)         // sprawdzenie czy gracz połączył przynajmniej 3 bloki
        {
            if (OnConnection != null)
            {
                OnConnection.Invoke(ConnectedBlocks.Count);
            }
            Board.RemoveBlocks(ConnectedBlocks); // usuwanie poszczególnych bloków
            Board.RefreshBlocks();               // przesunięcie poszczególnych elementów na planszy
        }


        ConnectedBlocks.Clear();

        CurrentColor = null;
        RefreshConnector();
    }
コード例 #28
0
    private void FinishConnection()
    {
        ConnectedBlocks
        .ForEach(block => block.IsConnected = false);

        if (ConnectedBlocks.Count >= 3)
        {
            if (OnConnection != null)
            {
                OnConnection.Invoke(ConnectedBlocks.Count);
            }

            Board.RemoveBlocks(ConnectedBlocks);
            Board.RefreshBlocks();
        }

        ConnectedBlocks.Clear();

        CurrentColor = null;
        RefreshConnection();
    }
コード例 #29
0
ファイル: ClientSocketSync.cs プロジェクト: tinshen/pidDev
        /// <summary>
        /// 连接
        /// </summary>
        /// <returns>成功返回TRUE</returns>
        public bool ConnectionServer()
        {
            try
            {
                IPEndPoint _ip = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(ip), port);
                this.Connect(_ip);
                this.SendBufferSize    = _SendBufferSize;
                this.ReceiveBufferSize = _ReceiveBufferSize;

                OnConnection.BeginInvoke(null, null);
                Thread t = new Thread(Receive);//数据返回监视
                t.IsBackground = true;
                t.Priority     = ThreadPriority.Lowest;
                t.Start();
                return(true);
            }
            catch (Exception e)
            {
                Error_Message = e.Message;
                OnError(e.Message);
                return(false);
            }
        }
コード例 #30
0
ファイル: MqttService.cs プロジェクト: ervinnotari/Bowling
 public async Task ConnectionStartAsync(Uri uri)
 {
     await Task.Run(() =>
     {
         try
         {
             _info   = new IBusService.ConnectionInfo(uri, MqttConfiguration.TopicMatcher(uri));
             _error  = null;
             _client = new MqttClient(uri.Host, uri.Port, false, null, null, MqttSslProtocols.None)
             {
                 ProtocolVersion = MqttProtocolVersion.Version_3_1
             };
             var code = default(byte);
             if (string.IsNullOrEmpty(uri.UserInfo))
             {
                 code = _client.Connect(Guid.NewGuid().ToString());
             }
             else
             {
                 var bUri = new UriBuilder(uri);
                 code     = _client.Connect(Guid.NewGuid().ToString(), bUri.UserName, bUri.Password);
             }
             _client.Subscribe(new[] { _info.Topic }, new[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
             _client.MqttMsgPublishReceived += DefaultClient_MqttMsgPublishReceived;
             OnConnection?.Invoke(code);
         }
         catch (Exception e)
         {
             _error = e;
         }
         finally
         {
             OnStatusChange?.Invoke(GetConnectionStatus(), _info);
         }
     });
 }