private void HandleDatagramReceived(IAsyncResult ar) { if (!IsRunning) { return; } try { TcpClientState internalClient = (TcpClientState)ar.AsyncState; //if (!internalClient.TcpClient.Connected) return; NetworkStream networkStream = internalClient.NetworkStream; int numberOfReadBytes = 0; try { // if the remote host has shutdown its connection, // read will immediately return with zero bytes. numberOfReadBytes = networkStream.EndRead(ar); } catch (Exception ex) { numberOfReadBytes = 0; } Debug.Log("HandleDatagramReceived:" + numberOfReadBytes); if (numberOfReadBytes == 0) { // connection has been closed TcpClientState internalClientToBeThrowAway; string tcpClientKey = internalClient.TcpClient.Client.RemoteEndPoint.ToString(); if (_clients.ContainsKey(tcpClientKey)) { _clients.Remove(tcpClientKey); } RaiseClientDisconnected(internalClient.TcpClient); return; } // received byte and trigger event notification byte[] receivedBytes = new byte[numberOfReadBytes]; Buffer.BlockCopy(internalClient.Buffer, 0, receivedBytes, 0, numberOfReadBytes); RaiseDatagramReceived(internalClient.TcpClient, receivedBytes); RaisePlaintextReceived(internalClient.TcpClient, receivedBytes); // continue listening for tcp datagram packets ContinueReadBuffer(internalClient, networkStream); } catch (InvalidOperationException ex) { Debug.Log("HandleDatagramReceived:" + ex.Message); } }
private void ContinueReadBuffer(TcpClientState internalClient, NetworkStream networkStream) { try { networkStream.BeginRead(internalClient.Buffer, 0, internalClient.Buffer.Length, HandleDatagramReceived, internalClient); } catch (ObjectDisposedException ex) { Debug.Log("ContinueReadBuffer:" + ex.Message); } }
private void HandleTcpClientAccepted(IAsyncResult ar) { if (!IsRunning) { return; } TcpListener tcpListener = (TcpListener)ar.AsyncState; TcpClient tcpClient = tcpListener.EndAcceptTcpClient(ar); if (!tcpClient.Connected) { return; } byte[] buffer = new byte[tcpClient.ReceiveBufferSize]; TcpClientState internalClient = new TcpClientState(tcpClient, buffer); // add client connection to cache string tcpClientKey = internalClient.TcpClient.Client.RemoteEndPoint.ToString(); if (_clients.ContainsKey(tcpClientKey)) { _clients[tcpClientKey] = internalClient; } else { _clients.Add(tcpClientKey, internalClient); } RaiseClientConnected(tcpClient); // begin to read data NetworkStream networkStream = internalClient.NetworkStream; ContinueReadBuffer(internalClient, networkStream); // keep listening to accept next connection ContinueAcceptTcpClient(tcpListener); }