コード例 #1
0
        public void FireDisconnectEvent(int connectionId, byte reason)
        {
            Disconnect?.Invoke(connectionId, reason);

            Connections[connectionId].Cleanup();
            Connections.Remove(connectionId);
        }
コード例 #2
0
        // Установка ника при подключении, в конце ожидается ответ от сервера об успешном подключении
        public static void SetUsername()
        {
            if (_tcpClient != null)
            {
                var    stream = _tcpClient.GetStream();
                var    buffer = new byte[2048];
                string data   = null;
                int    i;

                while ((i = stream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    data = Encoding.Unicode.GetString(buffer, 0, i);

                    if (IsOkMessage(data))
                    {
                        SendOkMessage();
                        break;
                    }

                    SetMessage?.Invoke(data, true);
                }

                if (NeedDisconnect(i))
                {
                    Disconnect?.Invoke();
                }
            }
        }
コード例 #3
0
        public virtual void Send(byte[] data)
        {
            try
            {
                _SendObj.Send(data);
            }
            catch (ObjectDisposedException)
            {
                IsConn = false;
                Disconnect?.Invoke("与服务器断开连接");
            }
            catch (SocketException)
            {
                try
                {
                    wait.Dispose();
                    AsynEvent.Dispose();
                    _sock.Close();
                    _sock.Dispose();
                }
                catch { }

                IsConn = false;
                Disconnect?.Invoke("与服务器断开连接");
            }
        }
コード例 #4
0
        /// <summary>
        /// Callback method that MdsLib calls when a device connects or disconnects
        /// </summary>
        /// <param name="mdsevent">details of device connection/disconnection</param>
        public void OnDeviceConnectionEvent(MDSEvent mdsevent)
        {
            var method = ((NSString)mdsevent.BodyDictionary.ValueForKey(new NSString("Method")));

            if (method == new NSString("POST"))
            {
                // Device connected
                var bodyDict = (NSDictionary)mdsevent.BodyDictionary.ValueForKey(new NSString("Body"));
                var serial   = (NSString)bodyDict.ValueForKey(new NSString("Serial"));
                var connDict = (NSDictionary)bodyDict.ValueForKey(new NSString("Connection"));
                var uuid     = (NSString)connDict.ValueForKey(new NSString("UUID"));

                Debug.WriteLine($"MdsConnectionListener OnDeviceConnectionEvent CONNECTED: Serial {serial}");
                ConnectionComplete?.Invoke(this, new MdsConnectionListenerEventArgs(serial, new Guid(uuid)));
            }
            else if (method == new NSString("DEL"))
            {
                // Device disconnected
                var serial = ((NSString)mdsevent.BodyDictionary.ValueForKey(new NSString("Serial")));
                Debug.WriteLine($"MdsConnectionListener OnDeviceConnectionEvent DISCONNECTED: Serial {serial}");
                Disconnect?.Invoke(this, new MdsConnectionListenerEventArgs(serial));
            }
            else
            {
                throw new MdsException($"OnDeviceConnectionEvent unexpected method: {method}");
            }
        }
コード例 #5
0
        internal static void HandleRemovedEvent(int instanceId)
        {
            Logger.Log($"Joystick Removed: Instance [{ instanceId }]", LogPriority.Verbose);

            Disconnect?.Invoke(instanceId);
            openGamepads.Remove(instanceId);
        }
コード例 #6
0
ファイル: CloudClient.cs プロジェクト: kk3959/ZYNet
        public CloudClient(IContainer container)
        {
            SyncWaitDic      = new ConcurrentDictionary <long, ReturnEventWaitHandle>(10, 10000);
            AsyncCallDiy     = new ConcurrentDictionary <long, AsyncCalls>();
            CallBackDiy      = new ConcurrentDictionary <long, AsyncCalls>();
            AsyncRunDiy      = new ConcurrentDictionary <long, AsyncRun>();
            AsyncWaitTimeOut = new List <KeyValuePair <long, DateTime> >();
            FodyDir          = new Dictionary <Type, Type>();

            ClientManager              = container.Resolve <IConnectionManager>();
            ClientManager.BinaryInput += DataOn;
            ClientManager.Disconnect  += p => Disconnect?.Invoke(p);
            MillisecondsTimeout        = container.Resolve <TimeOutOptions>().MillisecondsTimeout;
            IsCheckAsyncTimeOut        = container.Resolve <TimeOutOptions>().IsCheckAsyncTimeOut;

            Sync = new ZYSync()
            {
                SyncSend       = SendData,
                SyncSendAsWait = SendDataAsWait
            };


            Module  = container.Resolve <IModuleDictionary>();
            IsClose = false;

            LoggerFactory = container.Resolve <ILoggerFactory>();
            Log           = new DefaultLog(LoggerFactory.CreateLogger <CloudClient>());

            Task.Run(new Action(CheckAsyncTimeOut));
        }
コード例 #7
0
ファイル: EyeWebTestForm.cs プロジェクト: mth128/AudioEye
 private void EyeWebTestForm_FormClosing(object sender, FormClosingEventArgs e)
 {
     if (connected)
     {
         Disconnect.Invoke(sender, e);
     }
     Application.Exit();
 }
コード例 #8
0
        /// <summary>
        /// Disconnect from a certain client reuse is false since the Socket object is removed from the list.
        /// </summary>
        /// <param name="sock">Socket to disconnect from</param>
        public void BeginDisconnect(Socket sock)
        {
            sock.Disconnect(false);
            SocketArgs args = new SocketArgs(sock);

            Connections.Remove(sock);
            Disconnect?.Invoke(this, args);
        }
 private void WebSocketConnection_OnClose(object sender, IWebSocketConnection webSocketConnection)
 {
     if (connections.TryRemove(webSocketConnection.Id, out Connection connection))
     {
         Disconnect?.Invoke(this, webSocketConnection);
         _logger.LogInformation($"WebSocketConnection: \"{webSocketConnection.Id}\" was closed", connection);
     }
 }
コード例 #10
0
        private void DisconnectCallback(IAsyncResult ar)
        {
            Connection.EndDisconnect(ar);

            SocketArgs args = new SocketArgs(Connection);

            Disconnect?.Invoke(this, args);
        }
コード例 #11
0
ファイル: MTRFXXAdapter.cs プロジェクト: wadimk/noolite
 public void Close()
 {
     ThreadSafeExec(true, () =>
     {
         timer.Change(Timeout.Infinite, READING_INTERVAL);
         device.Close();
         Disconnect?.Invoke(this);
     });
 }
コード例 #12
0
 private void OnDisconnect()
 {
     if (m_Socket != null)
     {
         m_Socket.Close();
         m_Socket = null;
     }
     Disconnect?.Invoke(this, EventArgs.Empty);
 }
コード例 #13
0
 private void OnDisconnect()
 {
     Disconnect?.Invoke(this, this);
     OutgoingCall = null;
     IncomingCall = null;
     Answer       = null;
     Drop         = null;
     Disconnect   = null;
 }
コード例 #14
0
ファイル: NetManager.cs プロジェクト: nuke-haus/RobustToolbox
 /// <inheritdoc />
 public void ClientDisconnect(string reason)
 {
     DebugTools.Assert(IsClient, "Should never be called on the server.");
     if (ServerChannel != null)
     {
         Disconnect?.Invoke(this, new NetDisconnectedArgs(ServerChannel, reason));
     }
     Shutdown(reason);
 }
コード例 #15
0
        private Task DisconnectHandler(WebSocketCloseStatus closeStatus, string closeReason)
        {
            var message = $"Websocket Connection Closed with following reason \"{closeReason}\" and StatusCode \"{closeStatus}\"";

            EmitLogs(LogLevel.Error, message);
            Disconnect?.Invoke(closeStatus, closeReason);

            return(Task.CompletedTask);
        }
コード例 #16
0
 private void RemoveScreen(Screen screen)
 {
     if (_screens.ContainsKey(screen.Handle))
     {
         PropertyChanging?.Invoke(this, new PropertyChangingEventArgs(nameof(Count)));
         _screens.Remove(screen.Handle);
         CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, screen));
         PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Count)));
         Disconnect?.Invoke(this, new ScreenEventArgs(screen));
     }
 }
コード例 #17
0
ファイル: WebSockets.cs プロジェクト: won21kr/Serac
        public async Task Close()
        {
            if (!Closed)
            {
                Closed = true;
                await WriteFrame(true, false, 8, new byte[0]);

                Disconnect?.Invoke(this, ClientClose);
                Stream.Close();
                throw new CloseException();
            }
        }
コード例 #18
0
 public void Stop()
 {
     if (!_client.SafeHandle.IsClosed || _client.Connected)
     {
         if (Disconnect != null)
         {
             Disconnect.Invoke(this, _client.RemoteEndPoint);
         }
         _client.Shutdown(SocketShutdown.Both);
         _client.Close();
     }
 }
コード例 #19
0
        public void Dispose()
        {
            Disconnect?.Invoke();

            if (m_Modules?.Any() == true)
            {
                foreach (var module in m_Modules)
                {
                    module.Dispose();
                }
            }
        }
コード例 #20
0
        private void HandleError(Socket clientSocket, Exception e = null)
        {
            if (clientSocket == null)
            {
                return;
            }

            clientSocket.Shutdown(SocketShutdown.Both);

            var disconnectionReason = e?.Message ?? string.Empty;

            Disconnect?.Invoke(this, new ConnectionEventArgs(clientSocket, disconnectionReason));
        }
コード例 #21
0
        private void ReceiveCompleted(object sender, SocketAsyncEventArgs e)
        {
            if (e.SocketError == SocketError.Success && e.BytesTransferred > 0)
            {
                var byteArray = new byte[e.BytesTransferred];
                Buffer.BlockCopy(e.Buffer, 0, byteArray, 0, e.BytesTransferred);

                _dataCache.AddRange(byteArray);

                if (!_isDecoding)
                {
                    DecodingPacket();
                }

                // 尾递归,处理一条数据后,再进行处理下一条
                StartReceive();
            }
            else
            {
                // 断开连接
                if (e.BytesTransferred == 0)
                {
                    // 主动断开
                    if (e.SocketError == SocketError.Success)
                    {
                        Console.WriteLine("主动断开");

                        // FIXME
                        Disconnected?.Invoke(this, "主动断开");
                    }
                    else
                    {
                        // 网络异常断开
                        Disconnected?.Invoke(this, e.SocketError.ToString());
                        Console.WriteLine("网络异常断开");
                    }
                }
            }
        }
コード例 #22
0
 private void ConnectClick(object sender, EventArgs e)
 {
     if (state == FormState.Connected)
     {
         Disconnect?.Invoke(this, null);
     }
     else
     {
         Connect?.Invoke(this, new ConnectEventArgs {
             ConnectionData = GatherConnectionData()
         });
     }
 }
コード例 #23
0
ファイル: Screen.cs プロジェクト: WildGenie/WIMP
        private void DisplaySettingsChanging(object sender, EventArgs e)
        {
            var i = ScreenManager.Info(Handle);

            if (i.IsEmpty())
            {
                Disconnect?.Invoke(this, EventArgs.Empty);
                return;
            }
            foreach (var p in _ChangingProperties)
            {
                PropertyChanging?.Invoke(this, new PropertyChangingEventArgs(p));
            }
        }
コード例 #24
0
ファイル: TreeNode.cs プロジェクト: Roy-Ermers/TES-30
 public void Delete()
 {
     foreach (TreeNode <t> child in children)
     {
         if (child.Disconnect != null)
         {
             child.Disconnect.Invoke(this, null);
         }
     }
     if (Disconnect != null)
     {
         Disconnect.Invoke(this, null);
     }
     Children.Clear();
 }
コード例 #25
0
ファイル: CliClient.cs プロジェクト: jpdante/HtcSharp
        public async Task Reader()
        {
            while (_namedPipeClientStream.IsConnected && !_cancellationTokenSource.IsCancellationRequested)
            {
                try {
                    var buffer = new char[1024];
                    int count  = await _streamReader.ReadAsync(buffer, 0, buffer.Length);

                    Console.Write(buffer, 0, count);
                } catch (Exception ex) {
                    Console.WriteLine(ex.Message);
                }
            }
            Disconnect?.Invoke();
        }
コード例 #26
0
        public override void OnDisconnect(WZClient session)
        {
            var Session = session as GSSession;

            if (Session.Player != null)
            {
                if (Session.Player.Character != null)
                {
                    Program.client
                    .SendAsync(new SCRem
                    {
                        Server = (byte)Program.ServerCode,
                        List   = new CliRemDto[] {
                            new CliRemDto {
                                btName = Session.Player.Character.Name.GetBytes()
                            }
                        }
                    });

                    PartyManager.CancelMatching(Session.Player);
                }
                Session.Player.Status = LoginStatus.NotLogged;

                using (var db = new GameContext())
                {
                    if (Session.Player.Account != null)
                    {
                        var acc = (from a in db.Accounts
                                   where a.AccountId == Session.Player.Account.ID
                                   select a).First();

                        acc.IsConnected = false;

                        db.Accounts.Update(acc);
                        db.SaveChanges();
                        Logger.ForAccount(Session).Information("Disconnecting...");
                    }
                }
                Session.Player.Account = null;
            }
            //db.SaveChanges();

            Session.Player = null;
            base.OnDisconnect(session);
            Disconnect?.Invoke(this, new WZServerEventArgs {
                session = Session
            });
        }
コード例 #27
0
        public bool DisconnectFromSW()
        {
            Logger.Log("Unloading add-in", XCad.Base.Enums.LoggerMessageSeverity_e.Debug);

            try
            {
                Disconnect?.Invoke(this);
                OnDisconnect();
                Dispose();
                return(true);
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                return(false);
            }
        }
コード例 #28
0
ファイル: SwAddInEx.cs プロジェクト: persadewh/xcad
        public bool DisconnectFromSW()
        {
            Logger.Log("Unloading add-in");

            try
            {
                Disconnect?.Invoke(this);
                OnDisconnect();
                Dispose();
                return(true);
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                return(false);
            }
        }
コード例 #29
0
        public async Task CreateWebSocketConnectionAsync(WebSocket webSocket,
                                                         WebSocketConnectionsOptions options,
                                                         Guid connectionId)
        {
            WebSocketConnection webSocketConnection = new WebSocketConnection(webSocket,
                                                                              options.ReceivePayloadBufferSize, connectionId);

            webSocketConnection.ReceiveText += OnReceiveText;
            OnConnect(webSocketConnection);

            await webSocketConnection.ReceiveMessagesUntilCloseAsync();

            if (webSocketConnection.CloseStatus.HasValue)
            {
                await webSocket.CloseAsync(webSocketConnection.CloseStatus.Value, webSocketConnection.CloseStatusDescription, CancellationToken.None);
            }
            Disconnect?.Invoke(this, webSocketConnection);
            webSocketConnection.ReceiveText -= OnReceiveText;
        }
コード例 #30
0
        /// <summary>
        /// Метод, открепляющий сокет и закрывающий соединения с ним
        /// </summary>
        /// <param name="e">Исключение, если оно возникает при работе с сокетом</param>
        public void Detach(Exception e)
        {
            //проверяем, что если сокет отключен, то, ничего не делаем.
            if (!_attached)
            {
                return;
            }

            lock (this)
            {
                //стандартная двойная проверка с блокировкой
                if (!_attached)
                {
                    return;
                }

                _attached = false;

                //очищаем очередь отправки данных на сокете.
                //раз дошло до этого места, то уже и не судьба - сокет сломан.
                foreach (var tuple in _sendQueue)
                {
                    _pool.Free(tuple.Item1);
                }

                //удаляем сокет
                _socket.Dispose();
                _isSendComplete = true;

                //очищаем буффер на прием
                _pool.Free(_readCommandBuffer);
                _readCommandBuffer = null;

                //очищаем очередь
                _sendQueue.Clear();
                _socket = null;
                _offset = 0;

                //вызываем событие дисконнекта сокета
                Disconnect?.Invoke(this, new UnhandledExceptionEventArgs(e, false));
            }
        }