CGC_Codes

EchoSocket

Jun 9th, 2017
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.24 KB | None | 0 0
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using iNet;
  5.  
  6. namespace iNet
  7. {
  8.     internal class EchoSocket : IDisposable
  9.     {
  10.         public Socket socket;
  11.  
  12.         public EchoSocket(bool UseIPv6) : this(TcpServerTest.port, UseIPv6) { }
  13.  
  14.         public EchoSocket(int Port, bool UseIPv6)
  15.         {
  16.             socket = new Socket(UseIPv6
  17.                 ? AddressFamily.InterNetworkV6
  18.                 : AddressFamily.InterNetwork,
  19.                 SocketType.Stream, ProtocolType.Tcp);
  20.             socket.SendTimeout = 10000;
  21.             socket.ReceiveTimeout = 10000;
  22.             socket.Connect(UseIPv6 ? "::1" : "127.0.0.1", Port);
  23.         }
  24.  
  25.         public EchoSocket(bool UseIPv6, byte[] msg) : this(UseIPv6)
  26.         {
  27.             int sent = socket.Send(msg);
  28.             if (sent != msg.Length)
  29.                 throw new Exception("EchoSocket sent " + sent + " bytes only");
  30.         }
  31.  
  32.         public EchoSocket(bool UseIPv6, string msg) :
  33.             this(UseIPv6, System.Text.Encoding.ASCII.GetBytes(msg))
  34.         {
  35.         }
  36.  
  37.         public void Dispose()
  38.         {
  39.             if (socket != null)
  40.             {
  41.                 socket.Close();
  42.                 socket = null;
  43.             }
  44.         }
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment