Ejemplo n.º 1
0
        public void FireDisconnectEvent(int connectionId, byte reason)
        {
            Disconnect?.Invoke(connectionId, reason);

            Connections[connectionId].Cleanup();
            Connections.Remove(connectionId);
        }
Ejemplo n.º 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();
                }
            }
        }
Ejemplo n.º 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("与服务器断开连接");
            }
        }
        /// <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}");
            }
        }
Ejemplo n.º 5
0
        internal static void HandleRemovedEvent(int instanceId)
        {
            Logger.Log($"Joystick Removed: Instance [{ instanceId }]", LogPriority.Verbose);

            Disconnect?.Invoke(instanceId);
            openGamepads.Remove(instanceId);
        }
Ejemplo n.º 6
0
        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));
        }
Ejemplo n.º 7
0
 private void EyeWebTestForm_FormClosing(object sender, FormClosingEventArgs e)
 {
     if (connected)
     {
         Disconnect.Invoke(sender, e);
     }
     Application.Exit();
 }
Ejemplo n.º 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);
     }
 }
Ejemplo n.º 10
0
        private void DisconnectCallback(IAsyncResult ar)
        {
            Connection.EndDisconnect(ar);

            SocketArgs args = new SocketArgs(Connection);

            Disconnect?.Invoke(this, args);
        }
Ejemplo n.º 11
0
 public void Close()
 {
     ThreadSafeExec(true, () =>
     {
         timer.Change(Timeout.Infinite, READING_INTERVAL);
         device.Close();
         Disconnect?.Invoke(this);
     });
 }
Ejemplo n.º 12
0
 private void OnDisconnect()
 {
     if (m_Socket != null)
     {
         m_Socket.Close();
         m_Socket = null;
     }
     Disconnect?.Invoke(this, EventArgs.Empty);
 }
Ejemplo n.º 13
0
 private void OnDisconnect()
 {
     Disconnect?.Invoke(this, this);
     OutgoingCall = null;
     IncomingCall = null;
     Answer       = null;
     Drop         = null;
     Disconnect   = null;
 }
Ejemplo n.º 14
0
 /// <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);
 }
Ejemplo n.º 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);
        }
Ejemplo n.º 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));
     }
 }
Ejemplo n.º 17
0
        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();
            }
        }
Ejemplo n.º 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();
     }
 }
Ejemplo n.º 19
0
        public void Dispose()
        {
            Disconnect?.Invoke();

            if (m_Modules?.Any() == true)
            {
                foreach (var module in m_Modules)
                {
                    module.Dispose();
                }
            }
        }
Ejemplo n.º 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));
        }
Ejemplo n.º 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("网络异常断开");
                    }
                }
            }
        }
Ejemplo n.º 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()
         });
     }
 }
Ejemplo n.º 23
0
        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));
            }
        }
Ejemplo n.º 24
0
 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();
 }
Ejemplo n.º 25
0
        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();
        }
Ejemplo n.º 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
            });
        }
Ejemplo n.º 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);
            }
        }
Ejemplo n.º 28
0
        public bool DisconnectFromSW()
        {
            Logger.Log("Unloading add-in");

            try
            {
                Disconnect?.Invoke(this);
                OnDisconnect();
                Dispose();
                return(true);
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                return(false);
            }
        }
        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;
        }
Ejemplo n.º 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));
            }
        }