bobmarley12345

tcp thingy

Jun 4th, 2019 (edited)
839
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.48 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9.  
  10. // forgot who actually made this originally, but i just made a few changes to it
  11. namespace tcpthingy
  12. {
  13.     public class NetConnection
  14.     {
  15.         public delegate void NetConnectionEventHandler<TEventArgs>(object sender, NetConnection connection, TEventArgs e);
  16.         public delegate void NetConnectionEventHandler(object sender, NetConnection connection);
  17.  
  18.         private TcpClient client;
  19.         private TcpListener listener;
  20.         private List<Task> tasks = new List<Task>();
  21.  
  22.         public event NetConnectionEventHandler OnConnect;
  23.         public event NetConnectionEventHandler OnDisconnect;
  24.         public event NetConnectionEventHandler<byte[]> OnDataReceived;
  25.  
  26.         public int BufferSize = 1024;
  27.  
  28.         public EndPoint RemoteEndPoint
  29.         {
  30.             get
  31.             {
  32.                 if (client == null)
  33.                     throw new InvalidOperationException("Client is not connected");
  34.                 return client.Client.RemoteEndPoint;
  35.             }
  36.         }
  37.  
  38.         public NetConnection()
  39.         {
  40.  
  41.         }
  42.  
  43.         private NetConnection(TcpClient client)
  44.         {
  45.             this.client = client;
  46.         }
  47.         /// <summary>
  48.         /// Connects to a server on <paramref name="hostname"/> at a given <paramref name="port"/>
  49.         /// </summary>
  50.         /// <param name="hostname"></param>
  51.         /// <param name="port"></param>
  52.         public void Connect(string hostname, int port)
  53.         {
  54.             CheckServerUsedAsClient();
  55.             CheckClientAlreadyConnected();
  56.  
  57.             client = new TcpClient();
  58.             client.Connect(hostname, port);
  59.  
  60.             CallOnConnect(this);
  61.  
  62.             StartReceiveFrom(this);
  63.         }
  64.         /// <summary>
  65.         /// Connects to a server on IPAddress <paramref name="address"/>
  66.         /// </summary>
  67.         /// <param name="address"></param>
  68.         /// <param name="port"></param>
  69.         public void Connect(IPAddress address, int port)
  70.         {
  71.             CheckServerUsedAsClient();
  72.             CheckClientAlreadyConnected();
  73.  
  74.             client = new TcpClient();
  75.             client.Connect(address, port);
  76.  
  77.             CallOnConnect(this);
  78.  
  79.             StartReceiveFrom(this);
  80.         }
  81.         /// <summary>
  82.         /// Disconnects from the currently connected server
  83.         /// </summary>
  84.         public void Disconnect()
  85.         {
  86.             CheckServerUsedAsClient();
  87.             CallOnDisconnect(this);
  88.             client.GetStream().Close();
  89.             client.Close();
  90.         }
  91.         /// <summary>
  92.         /// Starts a server on a given port
  93.         /// <para>
  94.         /// INFO This will probably ask you to authenticate a windows firewall
  95.         /// connection. It should be on private for sending within a LAN.
  96.         /// </para>
  97.         /// </summary>
  98.         /// <param name="port"></param>
  99.         public void Start(int port)
  100.         {
  101.             Start(IPAddress.Any, port);
  102.         }
  103.         /// <summary>
  104.         /// Starts a server on a given IPAddress and port.
  105.         /// <para>
  106.         /// INFO This will probably ask you to authenticate a windows firewall
  107.         /// connection. It should be on private for sending within a LAN.
  108.         /// </para>
  109.         /// </summary>
  110.         /// <param name="address"></param>
  111.         /// <param name="port"></param>
  112.         public void Start(IPAddress address, int port)
  113.         {
  114.             CheckClientUsedAsServer();
  115.             CheckServerAlreadyStarted();
  116.  
  117.             listener = new TcpListener(address, port);
  118.             listener.Start();
  119.  
  120.             StartListen();
  121.         }
  122.         /// <summary>
  123.         /// Stops a currently running server
  124.         /// </summary>
  125.         public void Stop()
  126.         {
  127.             CheckClientUsedAsServer();
  128.             listener.Stop();
  129.             listener = null;
  130.             //tasks.Remove(ListenAsync());
  131.             //Task.WhenAll(tasks).Wait();
  132.         }
  133.         /// <summary>
  134.         /// Sends a byte array of data to the server.
  135.         /// <para>
  136.         /// use Encoding.ASCII.GetBytes(aString) to convert a string to byte and write the whole array
  137.         /// <para>
  138.         /// use Encoding.ASCII.GetString(byte) to convert a byte to a string and read it.
  139.         /// </para>
  140.         /// </para>
  141.         /// </summary>
  142.         /// <param name="data"></param>
  143.         public void Send(byte[] data)
  144.         {
  145.             CheckServerUsedAsClient();
  146.             client.GetStream().Write(data, 0, data.Length);
  147.         }
  148.  
  149.         private void CallOnDataReceived(NetConnection connection, byte[] data)
  150.         {
  151.             if (OnDataReceived != null)
  152.                 OnDataReceived(this, connection, data);
  153.         }
  154.         private void CallOnConnect(NetConnection client)
  155.         {
  156.             if (OnConnect != null)
  157.                 OnConnect(this, client);
  158.         }
  159.         private void CallOnDisconnect(NetConnection client)
  160.         {
  161.             if (OnDisconnect != null)
  162.                 OnDisconnect(this, client);
  163.         }
  164.  
  165.         private void CheckServerUsedAsClient()
  166.         {
  167.             if (listener != null)
  168.                 throw new InvalidOperationException("Cannot use a server connection as a client");
  169.         }
  170.         private void CheckClientUsedAsServer()
  171.         {
  172.             if (client != null)
  173.                 throw new InvalidOperationException("Cannot use a client connection as a server");
  174.         }
  175.         private void CheckServerAlreadyStarted()
  176.         {
  177.             if (listener != null)
  178.                 throw new InvalidOperationException("Server is already started");
  179.         }
  180.         private void CheckClientAlreadyConnected()
  181.         {
  182.             if (client != null)
  183.                 throw new InvalidOperationException("Client is already connected");
  184.         }
  185.  
  186.         private void StartListen()
  187.         {
  188.             tasks.Add(ListenAsync());
  189.         }
  190.         private async Task ListenAsync()
  191.         {
  192.             while (true)
  193.             {
  194.                 TcpClient client = await listener.AcceptTcpClientAsync();
  195.                 NetConnection connection = new NetConnection(client);
  196.                 StartReceiveFrom(connection);
  197.                 OnConnect(this, connection);
  198.             }
  199.         }
  200.  
  201.         private void StartReceiveFrom(NetConnection client)
  202.         {
  203.             tasks.Add(ReceiveFromAsync(client));
  204.         }
  205.         private async Task ReceiveFromAsync(NetConnection client)
  206.         {
  207.             try
  208.             {
  209.                 NetworkStream stream = client.client.GetStream();
  210.                 byte[] buffer = new byte[BufferSize];
  211.                 MemoryStream ms = new MemoryStream();
  212.                 while (client.client.Connected)
  213.                 {
  214.                     int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
  215.                     ms.Write(buffer, 0, bytesRead);
  216.                     if (!stream.DataAvailable)
  217.                     {
  218.                         CallOnDataReceived(client, ms.ToArray());
  219.                         ms.Seek(0, SeekOrigin.Begin);
  220.                         ms.SetLength(0);
  221.                     }
  222.                 }
  223.                 CallOnDisconnect(client);
  224.             }
  225.             catch
  226.             {
  227.                 CallOnDisconnect(client);
  228.                 throw;
  229.             }
  230.         }
  231.     }
  232. }
Advertisement
Add Comment
Please, Sign In to add comment