/// <summary> /// Disconnects the session with the given reason. /// </summary> /// <param name="reason">The reason for the disconnect.</param> public async Task DisconnectAsync(string reason) { try { if (!IsConnected) { return; } Logger.Info($"Session {Id} disconnecting: {reason}"); if (null != _socket) { await _socket.DisconnectAsync(false).ConfigureAwait(false); } else if (null != _sslSocket) { await _sslSocket.DisconnectAsync(false).ConfigureAwait(false); } DisconnectedEvent?.Invoke(this, new DisconnectedEventArgs { Reason = reason } ); } catch (SocketException e) { Logger.Error("Error disconnecting socket!", e); } }
private void SafeInvokeDisconnected() { if (this.Disconnected == null) { return; //No Listeners } DisconnectedEvent listener = null; Delegate[] dels = this.Disconnected.GetInvocationList(); foreach (Delegate del in dels) { try { listener = (DisconnectedEvent)del; listener.Invoke(); } catch (Exception) { //Could not reach the destination, so remove it //from the list this.Disconnected -= listener; } } }
void HandleDisconnectedEvent() { if (DisconnectedEvent != null) { DisconnectedEvent.Invoke(); } }
public MessageHandlerResult HandleMessage(Message request) { Client client = clientRepository.GetByID(request.clientId); var e = new DisconnectedEvent(client); EventHub.Publish(e); clientRepository.RemoveByID(client.ID); Message[] message = { new Message { id = request.id, channel = this.ChannelName, successful = true, clientId = request.clientId } }; return(new MessageHandlerResult { Message = message, ShouldWait = false }); }
public override void OnCreated() { Log = LogManager.GetLogger(string.Format("ChatClient<NetId:{0}>", Channel.Id)); SetHandler <IChatLogin>(this); DisconnectedEvent.Subscribe(OnDisconnectAsync); Log.Info("connected"); }
void HandleDisconnectedEvent(IConnection conn) { if (DisconnectedEvent != null) { DisconnectedEvent.Invoke(conn); } }
/// <summary> /// Raised by the underlying <see cref="Connection"/> when a connection is destroyed /// </summary> private void Connection_DisconnectedEvent(object sender, EventArgs e) { // Just pass on the event along var args = new object[] { sender, e }; DisconnectedEvent.RaiseEventSafe(ref args); }
public void Disconnect() { if (!IsActive) { return; } if (m_Connection.ConnectionId != NetworkTransport.INVALID_CONNECTION) { byte error; UNET.NetworkTransport.Disconnect(m_Connection.SocketId, m_Connection.ConnectionId, out error); m_Connection.ConnectionId = NetworkTransport.INVALID_CONNECTION; m_Connection.LastError = (NetworkError)error; } if (m_State == ConnectState.Connected) { m_State = ConnectState.Disconnected; m_Connection.IsConnected = false; m_ServerIp = string.Empty; m_ServerPort = 0; InternalRemoveHost(); if (DisconnectedEvent != null) { DisconnectedEvent.Invoke(); } } else { HandleConnectingFailed(); } }
private async Task <byte[]> GetMessageAsync() { byte[] result = null; try { Byte[] receivedBytes = new byte[1024]; Debug.Log("Reading from stream"); int receivedAmount = await networkStream.ReadAsync(receivedBytes, 0, receivedBytes.Length); result = TrimBytes(receivedBytes, receivedAmount); Debug.Log($"Received data {receivedAmount}"); } catch (ObjectDisposedException ex) { Debug.LogWarning("Connection lost with the server with ex:" + ex.ToString()); } catch (Exception ex) { Debug.LogError("Exception : " + ex.ToString()); } finally { if (!client.Connected) { disposed = true; Debug.Log("Connection lost :("); mainThreadService.SendToMainThread(() => { DisconnectedEvent?.Invoke(); }); } } return(result); }
/// <summary> /// Start Running Receiving Process. /// </summary> public void RunReceive() { try { bool res = false; do { if (m_AsyncReceive == null) //Disposed { break; } lock (m_SyncRoot) { res = !m_CurrentChannel.ReceiveAsync(m_AsyncReceive); } if (res) { ProceedReceiving(m_AsyncReceive); } }while (res); } catch (Exception e) { Logger.Trace(e.ToString()); DisconnectedEvent?.Invoke(this, EventArgs.Empty); } }
public bool Send(byte[] data) { int length = data.Length; lock (_syncTcp) { if (ConnectionStatus == ConnectionStatusEnum.ConnectedInicialized || ConnectionStatus == ConnectionStatusEnum.ConnectedNotInicialized) { try { _netStream.Write(data, 0, length); return(true); } catch (IOException) //timeout { ConnectionStatus = ConnectionStatusEnum.Disconnected; DisconnectedEvent.Set(); if (AutoReconnect) { Connect(); } } } } return(false); }
/// <summary> /// Loop that listens for data and raises events when data is received. /// </summary> private async Task DataReceiver(CancellationToken token) { Logger.Log(Logger.Level.Debug, $"Currently monitoring socket for incoming data"); try { // Loop forever. That's a long time while (true) { // Determine if we can loop if (token.IsCancellationRequested || Client == null || !Client.Connected) { Logger.Log(Logger.Level.Debug, $"Halting socket monitoring..."); break; } // Read data. This should not return until data is received byte[] data = await DataReadAsync(token); // Obviously, if there's no data, there's an issue if (data == null) { Logger.Log(Logger.Level.Warning, $"Read null bytes from the socket. Skipping..."); // Wait for a bit and try again await Task.Delay(30); continue; } Logger.Log(Logger.Level.Debug, $"Read {data.Length} bytes from the socket. Raising events."); // Raise the event unawaited so that we can keep looping in case more data comes in _ = Task.Run(() => { var args = new object[] { this, new DataReceivedEventArgs(data) }; DataReceivedEvent.RaiseEventSafe(ref args); }); } } catch (TaskCanceledException) { // We don't really care if the task was cancelled. } catch (OperationCanceledException) { // We don't really care if the task was cancelled. } catch (Exception ex) { Logger.Log(Logger.Level.Error, $"An error occurred monitoring the socket for data.\n\n{ex.Message}"); } Logger.Log(Logger.Level.Debug, $"Raising the {nameof(DisconnectedEvent)} event"); _ = Task.Run(() => { var args = new object[] { this, EventArgs.Empty }; DisconnectedEvent.RaiseEventSafe(ref args); }); }
/// <summary> /// Reading Length And Handles Data By [HandleReceived(byte[])] Without Length. /// </summary> /// <param name="e"></param> private void ProceedReceiving(SocketAsyncEventArgs e) { int transfered = e.BytesTransferred; if (e.SocketError != SocketError.Success || transfered <= 0) { DisconnectedEvent?.Invoke(this, EventArgs.Empty); return; } PacketReader reader = new PacketReader(m_RecvBuffer, 0); ushort length = reader.ReadLEUInt16(); ushort offset = 2; //обрабатываем слипшиеся пакеты //var path = "d:\\dump.txt"; while (length > 0 && offset < reader.Size) { byte[] data = new byte[length]; Buffer.BlockCopy(m_RecvBuffer, offset, data, 0, length); //--- Console Hexadecimal //сначало надо вывести лог пакета в консоль StringBuilder builder = new StringBuilder(); builder.Append("Recv: "); builder.Append(Utility.IntToHex(length)); builder.Append(" "); for (int i = 0; i < length; i++) { builder.AppendFormat("{0:X2} ", data[i]); } //не выводим Ping if (data[2] != 0x12) { Console.ForegroundColor = ConsoleColor.DarkGray; Logger.Trace(builder.ToString()); Console.ResetColor(); } #if DEBUG //--- File Hexadecimal //вывод лога пакетов в файл //не выводим Ping //if (data[2] != 0x12) //{ // var fs = new FileStream(path, FileMode.Append); // var sw = new StreamWriter(fs); // sw.WriteLine(builder.ToString()); // sw.Close(); // fs.Close(); //} #endif offset += length; reader.Offset = offset; length = reader.ReadLEUInt16(); //проверяем, есть ли еще пакет offset += 2; //и только затем отправить на обработку HandleReceived(data); //отправляем на обработку данные пакета } reader.Clear(); //почистим буфер, инача считываются старые данные reader = null; }
public void Handle(DisconnectedEvent message) { _dispatcherTimer.Stop(); IsConnected = false; IsConnecting = false; IsEditingEnabled = true; }
private void OnStateChange(Object sender, StateChangeEventArgs e) { Console.WriteLine("FIX session state: " + e.NewState.ToString()); if (e.NewState == SessionState.DISCONNECTED) { DisconnectedEvent.Set(); } }
/// <summary> /// Raised by the socket wrapper when a disconnection is detected /// </summary> private void ClientInstance_DisconnectedEvent(object sender, EventArgs e) { Logger.Log(Logger.Level.Info, "Disconnection detected. Passing on..."); // Pass the event on var args = new object[] { sender, EventArgs.Empty }; DisconnectedEvent.RaiseEventSafe(ref args); }
private void OnDisconnect() { if (level != null) { level.players.Remove(this); Visible = false; } DisconnectedEvent.Raise(server, this, quitMessage); }
public void Disconnected(string msg = "Error Connection.") { var login = _sessionClient.GetInfo(false).My.Login; //DiscordBotServer.Helpers.Loger.Log("Chat Disconected :( " + login); _sessionClient.Disconnect(); DisconnectedEvent?.Invoke(this, new StringWrapperEventArgument() { Message = login }); }
private void HandleClientDisconnected(object sender, EventArgs e) { IClient client = (IClient)sender; client.Disconnected -= HandleClientDisconnected; clientRepository.DeleteByID(client.ID); DisconnectedEvent disconnectedEvent = new DisconnectedEvent(client); EventHub.Publish(disconnectedEvent); }
/// <summary> /// Reading Length And Handles Data By [HandleReceived(byte[])] Without Length. /// </summary> /// <param name="e"></param> private void ProceedReceiving(SocketAsyncEventArgs e) { int transfered = e.BytesTransferred; if (e.SocketError != SocketError.Success || transfered <= 0) { DisconnectedEvent?.Invoke(this, EventArgs.Empty); return; } PacketReader reader = new PacketReader(m_RecvBuffer, 0); short length = reader.ReadLEInt16(); short offset = 2; //обрабатываем слипшиеся пакеты while (length > 0 && offset < reader.Size) { //--- Console Hexadecimal //TODO: в выводе в лог разделять слипшиеся пакеты StringBuilder builder = new StringBuilder(); builder.Append("Recv: "); for (int i = 0; i < transfered; i++) { builder.AppendFormat("{0:x2} ".ToUpper(), m_RecvBuffer[i]); } //не выводим Ping if (m_RecvBuffer[4] != 0x12) { Console.ForegroundColor = ConsoleColor.DarkGray; Logger.Trace(builder.ToString()); Console.ResetColor(); } //--- Console Hexadecimal //#if DEBUG //вывод лога пакетов в файл //string path = "d:\\dump.txt"; //The path to the file, ensure that files exist. //FileStream fs = new FileStream(path, FileMode.Append); //StreamWriter sw = new StreamWriter(fs); //sw.WriteLine(builder.ToString()); //sw.Close(); //fs.Close(); //#endif byte[] data = new byte[length]; Buffer.BlockCopy(m_RecvBuffer, offset, data, 0, length); HandleReceived(data); //отправляем на обработку данные пакета offset += length; reader.Offset = offset; length = reader.ReadLEInt16(); //проверяем, есть ли еще пакет offset += 2; } reader.Clear(); //почистим буфер, инача считываются старые данные reader = null; }
void InternalDisonnect(Connection conn) { byte disconnecingError; UNET.NetworkTransport.Disconnect(m_SocketId, conn.ConnectionId, out disconnecingError); conn.IsConnected = false; DisconnectedEvent?.Invoke(conn); m_Connections[conn.ConnectionId] = null; }
public void ConnectAndListen() { ServerSettingsLibrary.ServerData serverData = serverSettingsLibrary.GetCurrentServerData(); IPAddress localAddr = IPAddress.Parse(serverData.IpAddress); client = new TcpClient(); try { //Change to the ip adress of the server. client.Connect(localAddr, serverData.Port); Debug.Log("Connected to: " + client.Connected); } catch (SocketException ex) { Debug.LogError(ex.ToString()); } catch (Exception ex) { Debug.LogError(ex.ToString()); } finally { if (!client.Connected && retries < maxRetries) { retries++; ConnectAndListen(); } else if (retries == maxRetries) { //Not connected cancel. DisconnectedEvent?.Invoke(); } else { //Connected waiting for auth :) ConnectedEvent(); } } if (client.Connected) { networkStream = client.GetStream(); SentJoinMessage(); //Start listening Debug.Log("Start listen thread"); Task.Run(ListenAsync); } }
public static void HandleDisconnected(StateObject state) { // Notify that the user disconnected var e = new DisconnectedEventArgs(); DisconnectedEvent.Invoke(null, e); // Clear the current work Socket currentState.workSocket = null; // Start listening for a new connection StartAccept(state); }
private void SwitcherDisconnected() { if (m_switcher != null) { // Remove callback: m_switcher.RemoveCallback(this); // release reference: m_switcher = null; } nullifyMixEffectsBlocks(); DisconnectedEvent?.Invoke(this, new EventArgs()); }
private void RecvThreadProc() { while (tcpClient != null) { NetworkPacket packet; try { packet = NetworkPacket.Read(tcpClient.GetStream()); } catch (Exception e) { log.Info("Disconnected from peer: " + e.Message); break; } HandlePacket(packet); } DisconnectedEvent?.Invoke(this, EventArgs.Empty); }
void HandleDisconnectEvent() { if (m_State == ConnectState.Connecting) { HandleConnectingFailed(); } else { m_State = ConnectState.Disconnected; m_Connection.ConnectionId = NetworkTransport.INVALID_CONNECTION; m_Connection.IsConnected = false; m_ServerIp = string.Empty; m_ServerPort = 0; InternalRemoveHost(); DisconnectedEvent?.Invoke(); } }
/// <summary> /// Calls When We Need Send Data. /// </summary> private void M_AsyncSend_Do() { try { if (m_PacketQueue.Count > 0) { NetPacket packet = m_PacketQueue.Dequeue(); byte[] compiled = packet.Compile(); //--- Console Hexadecimal StringBuilder builder = new StringBuilder(); builder.Append("Send: "); // Logger.Trace(builder.ToString()); // builder.Clear(); foreach (byte b in compiled) { builder.AppendFormat("{0:X2} ", b); } //не выводим Pong if (compiled[4] != 0x13) { Console.ForegroundColor = ConsoleColor.Gray; Logger.Trace(builder.ToString()); Console.ResetColor(); } //--- Console Hexadecimal //#if DEBUG // string path = "d:\\dump.txt"; //The path to the file, ensure that files exist. // FileStream fs = new FileStream(path, FileMode.Append); // StreamWriter sw = new StreamWriter(fs); // sw.WriteLine(builder.ToString()); // sw.Close(); // fs.Close(); //#endif m_CurrentChannel.Send(compiled, compiled.Length, SocketFlags.None); } } catch (Exception e) { Logger.Trace(e.ToString()); DisconnectedEvent?.Invoke(this, EventArgs.Empty); } }
/// <summary> /// Odesla data a ihned ceka na odpoved. /// </summary> /// <param name="data">Data, ktera se odesilaji.</param> /// <param name="dataLength">Pocet bytu k odeslani.</param> /// <param name="answer">Odpoved</param> /// <param name="answerLength">Pocet bytu odpovedi.</param> /// <param name="log">Moznost definovat log</param> /// <returns>True, pokud odeasli a prijem probehlo.</returns> public bool SendReceive(byte[] data, int dataLength, ref byte[] answer, ref int answerLength, Func <byte[], int, bool> continueRead = null) { if (continueRead == null) { continueRead = (read, readLenght) => { return(false); }; } lock (_syncTcp) { if (ConnectionStatus == ConnectionStatusEnum.ConnectedInicialized || ConnectionStatus == ConnectionStatusEnum.ConnectedNotInicialized) { { try { _netStream.Write(data, 0, dataLength); answerLength = 0; do { answerLength += _netStream.Read(answer, answerLength, answer.Length); } while (continueRead(answer, answerLength)); return(true); } catch (IOException) //timeout { ConnectionStatus = ConnectionStatusEnum.Disconnected; DisconnectedEvent.Set(); if (AutoReconnect) { Connect(); } } } } } return(false); }
/// <summary> /// Calls When We Need Send Data /// </summary> private void M_AsyncSend_Do() { try { if (m_PacketQueue.Count <= 0) { return; } var packet = m_PacketQueue.Dequeue(); var compiled = packet.Compile(); m_CurrentChannel.Send(compiled, compiled.Length, SocketFlags.None); //отправляем пакет //--- Console Hexadecimal //вывод лога пакетов в консоль var builder = new StringBuilder(); builder.Append("Send: "); //builder.Append(Utility.IntToHex(compiled.Length)); //builder.Append(" "); foreach (var t in compiled) { builder.AppendFormat("{0:X2} ", t); } //не выводим Pong if (compiled[4] == 0x13) { return; } Console.ForegroundColor = ConsoleColor.Gray; Logger.Trace(builder.ToString()); Console.ResetColor(); } catch (Exception e) { Logger.Trace(e.ToString()); DisconnectedEvent?.Invoke(this, EventArgs.Empty); } }
/// <summary> /// Polls the session socket and reads all of the available data. /// </summary> /// <param name="microSeconds">The microsecond poll timeout.</param> public async Task PollAndReceiveAllAsync(int microSeconds) { if (!IsConnected) { return; } using (MemoryStream stream = new MemoryStream()) { int count = -1; if (null != _socket) { count = await _socket.PollAndReceiveAllAsync(microSeconds, stream).ConfigureAwait(false); } else if (null != _sslSocket) { count = await _sslSocket.PollAndReceiveAllAsync(microSeconds, stream).ConfigureAwait(false); } if (count < 0) { Logger.Warn($"Session {Id} remote disconnected!"); DisconnectedEvent?.Invoke(this, new DisconnectedEventArgs { Reason = Resources.DisconnectSocketClosed } ); return; } if (0 == count) { return; } byte[] data = stream.ToArray(); await OnDataReceivedAsync(data, 0, data.Length).ConfigureAwait(false); } }