/// <summary>Callback for BeginReceive</summary> /// <param name="ar"></param> private void ReceiveCallback(IAsyncResult ar) { try { Socket sock = (Socket)ar.AsyncState; int size = sock.EndReceive(ar); if (this.socket != sock) { this.Close("Async Receive Socket mismatched"); return; } if (size < 1) { this.Close("No Bytes Received"); return; } if (DataArrived != null) { var localData = new byte[size]; Array.Copy(byteBuffer, localData, size); var net = new NetSockDataArrivalEventArgs(this, localData); DataArrived(this, net); } this.socket.BeginReceive(this.byteBuffer, 0, this.byteBuffer.Length, SocketFlags.None, new AsyncCallback(this.ReceiveCallback), this.socket); } catch (ObjectDisposedException) { return; // socket disposed, let it die quietly } catch (SocketException ex) { if (ex.SocketErrorCode == SocketError.ConnectionReset) { this.Close("Remote Socket Closed"); } else { throw; } } catch (Exception ex) { this.Close("Socket Receive Exception"); this.OnErrorReceived("Socket Receive", ex); } }
private void client_DataArrived(object sender, NetSockDataArrivalEventArgs e) { string msg; if (e.Data.Length > 100) { msg = "!too long!"; } else msg = Encoding.ASCII.GetString(e.Data); this.Log("Recieved: " + msg + " (" + e.Data.Length.ToString() + " bytes)"); }