SHARE
TWEET

NetConnectionThingy

a guest Apr 21st, 2019 54 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public class NetConnection
  2.     {
  3.         public delegate void NetConnectionEventHandler<TEventArgs>(object sender, NetConnection connection, TEventArgs e);
  4.         public delegate void NetConnectionEventHandler(object sender, NetConnection connection);
  5.  
  6.         private TcpClient client;
  7.         private TcpListener listener;
  8.         private List<Task> tasks = new List<Task>();
  9.  
  10.         public event NetConnectionEventHandler OnConnect;
  11.         public event NetConnectionEventHandler OnStart;
  12.         public event NetConnectionEventHandler OnDisconnect;
  13.         public event NetConnectionEventHandler<byte[]> OnDataReceived;
  14.  
  15.         public int BufferSize = 1024;
  16.  
  17.         public EndPoint RemoteEndPoint
  18.         {
  19.             get
  20.             {
  21.                 if (client == null)
  22.                     throw new InvalidOperationException("Client is not connected");
  23.                 return client.Client.RemoteEndPoint;
  24.             }
  25.         }
  26.  
  27.         public NetConnection()
  28.         {
  29.  
  30.         }
  31.  
  32.         private NetConnection(TcpClient client)
  33.         {
  34.             this.client = client;
  35.         }
  36.         public void Connect(string hostname, int port)
  37.         {
  38.             CheckServerUsedAsClient();
  39.             CheckClientAlreadyConnected();
  40.  
  41.             client = new TcpClient();
  42.             client.Connect(hostname, port);
  43.  
  44.             CallOnConnect(this);
  45.  
  46.             StartReceiveFrom(this);
  47.         }
  48.         public void Connect(IPAddress address, int port)
  49.         {
  50.             CheckServerUsedAsClient();
  51.             CheckClientAlreadyConnected();
  52.  
  53.             client = new TcpClient();
  54.             client.Connect(address, port);
  55.  
  56.             CallOnConnect(this);
  57.  
  58.             StartReceiveFrom(this);
  59.         }
  60.         public void Disconnect()
  61.         {
  62.             CheckServerUsedAsClient();
  63.             CallOnDisconnect(this);
  64.             client.Close();
  65.         }
  66.         public void Start(int port)
  67.         {
  68.             IPAddress ip = IPAddress.Any;
  69.             Start(ip, port);
  70.             CallOnStart(this);
  71.         }
  72.         public void Start(IPAddress address, int port)
  73.         {
  74.             CheckClientUsedAsServer();
  75.             CheckServerAlreadyStarted();
  76.  
  77.             listener = new TcpListener(address, port);
  78.             listener.Start();
  79.  
  80.             StartListen();
  81.         }
  82.         public void Stop()
  83.         {
  84.             CheckClientUsedAsServer();
  85.             listener.Stop();
  86.             Task.WhenAll(tasks).Wait();
  87.         }
  88.  
  89.         public void Send(byte[] data)
  90.         {
  91.             CheckServerUsedAsClient();
  92.             client.GetStream().Write(data, 0, data.Length);
  93.         }
  94.  
  95.         private void CallOnDataReceived(NetConnection connection, byte[] data)
  96.         {
  97.             if (OnDataReceived != null)
  98.                 OnDataReceived(this, connection, data);
  99.         }
  100.         private void CallOnConnect(NetConnection client)
  101.         {
  102.             if (OnConnect != null)
  103.                 OnConnect(this, client);
  104.         }
  105.         private void CallOnStart(NetConnection server)
  106.         {
  107.             if (OnStart != null)
  108.                 OnStart(this, server);
  109.         }
  110.         private void CallOnDisconnect(NetConnection client)
  111.         {
  112.             if (OnDisconnect != null)
  113.                 OnDisconnect(this, client);
  114.         }
  115.         /// <summary>
  116.         /// Throws an exception if the listner is not active
  117.         /// </summary>
  118.         private void CheckServerUsedAsClient()
  119.         {
  120.             if (listener != null)
  121.                 throw new InvalidOperationException("Cannot use a server connection as a client");
  122.         }
  123.         private void CheckClientUsedAsServer()
  124.         {
  125.             if (client != null)
  126.                 throw new InvalidOperationException("Cannot use a client connection as a server");
  127.         }
  128.         private void CheckServerAlreadyStarted()
  129.         {
  130.             if (listener != null)
  131.                 throw new InvalidOperationException("Server is already started");
  132.         }
  133.         private void CheckClientAlreadyConnected()
  134.         {
  135.             if (client != null)
  136.                 throw new InvalidOperationException("Client is already connected");
  137.         }
  138.  
  139.         private void StartListen()
  140.         {
  141.             tasks.Add(ListenAsync());
  142.         }
  143.         private async Task ListenAsync()
  144.         {
  145.             while (true)
  146.             {
  147.                 TcpClient client = await listener.AcceptTcpClientAsync();
  148.                 NetConnection connection = new NetConnection(client);
  149.                 StartReceiveFrom(connection);
  150.                 OnConnect(this, connection);
  151.             }
  152.         }
  153.  
  154.         private void StartReceiveFrom(NetConnection client)
  155.         {
  156.             tasks.Add(ReceiveFromAsync(client));
  157.         }
  158.         private async Task ReceiveFromAsync(NetConnection client)
  159.         {
  160.             try
  161.             {
  162.                 NetworkStream stream = client.client.GetStream();
  163.                 byte[] buffer = new byte[BufferSize];
  164.                 MemoryStream ms = new MemoryStream();
  165.                 while (client.client.Connected)
  166.                 {
  167.                     int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
  168.                     ms.Write(buffer, 0, bytesRead);
  169.                     if (!stream.DataAvailable)
  170.                     {
  171.                         CallOnDataReceived(client, ms.ToArray());
  172.                         ms.Seek(0, SeekOrigin.Begin);
  173.                         ms.SetLength(0);
  174.                     }
  175.                 }
  176.                 CallOnDisconnect(client);
  177.             }
  178.             catch
  179.             {
  180.                 CallOnDisconnect(client);
  181.                 throw;
  182.             }
  183.         }
  184.     }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top