SHARE
TWEET

Untitled

a guest Dec 15th, 2019 58 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Text;
  5. using System.Threading;
  6.  
  7. namespace Comm_Distance
  8. {
  9.     // Object state for asynchronous reading of Client data
  10.     public class StateObject
  11.     {
  12.         // Socket client
  13.         public Socket workSocket = null;
  14.  
  15.         // Buffer size
  16.         public const int BufferSize = 1024;
  17.  
  18.         // Buffer reception
  19.         public byte[] buffer = new byte[BufferSize];
  20.  
  21.         // Reception data string
  22.         public StringBuilder sb = new StringBuilder();
  23.     }
  24.  
  25.     public class AsynchronousSocketListener
  26.     {
  27.         // Thread signal
  28.         public static ManualResetEvent allDone = new ManualResetEvent(false);
  29.  
  30.         public AsynchronousSocketListener()
  31.         {
  32.  
  33.         }
  34.  
  35.         public static void StartListening()
  36.         {
  37.             /* Establish local endpoint for socket
  38.              Device DNS is running listener
  39.              which is "192.168.56.1"
  40.             */
  41.             IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
  42.             IPAddress ipAddress = ipHostInfo.AddressList[0];
  43.             IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
  44.  
  45.             // TCP / IP socket creation
  46.             Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  47.  
  48.             // Bind the socket to the local endpoint and listen for incoming connections
  49.             try
  50.             {
  51.                 listener.Bind(localEndPoint);
  52.                 listener.Listen(100);
  53.  
  54.                 while (true)
  55.                 {
  56.                     // Set the event to an unreported state
  57.                     allDone.Reset();
  58.  
  59.                     // Start asynchronous socket to listen for connections
  60.                    
  61.                     Console.WriteLine("Waiting for a connection...");
  62.                     listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
  63.  
  64.                     // Wait for a connection to be established before continuing
  65.                    
  66.                     allDone.WaitOne();
  67.                 }
  68.             }
  69.             catch (Exception e)
  70.             {
  71.                 Console.WriteLine(e.ToString());
  72.  
  73.             }
  74.  
  75.             Console.WriteLine("\nPress ENTER to continue...");
  76.             Console.Read();
  77.         }
  78.  
  79.         public static void AcceptCallback(IAsyncResult ar)
  80.         {
  81.             // Signal to the main thread to continue
  82.             allDone.Set();
  83.  
  84.             // Gets the socket that handles the client request
  85.             Socket listener = (Socket)ar.AsyncState;
  86.             Socket handler = listener.EndAccept(ar);
  87.  
  88.             // Create Object state
  89.             StateObject state = new StateObject();
  90.             state.workSocket = handler;
  91.             handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
  92.         }
  93.  
  94.         public static void ReadCallback(IAsyncResult ar)
  95.         {
  96.             string content = string.Empty;
  97.             /*Get status object and manager socket
  98.              * from the asynchronous state object
  99.              */
  100.             StateObject state = (StateObject)ar.AsyncState;
  101.             Socket handler = state.workSocket;
  102.  
  103.             // Read the data from the client socket
  104.             int bytesRead = handler.EndReceive(ar);
  105.  
  106.             if (bytesRead > 0)
  107.             {
  108.                 // If there is more data, then we store the data received so far
  109.                 state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
  110.  
  111.                 // Checks the end of file tag. If it's not good, read more data
  112.                 content = state.sb.ToString();
  113.                 if (content.IndexOf("<EOF>") > -1)
  114.                 {
  115.                     /* All data has been read from the client
  116.                        Display on the console
  117.                      */
  118.                     Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content);
  119.  
  120.                     // Return data to client
  121.                     Send(handler, content);
  122.                 }
  123.                 else
  124.                 {
  125.                     // If all the data have not been received. Take more.
  126.                     handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback),
  127.                         state);
  128.                 }
  129.             }
  130.         }
  131.  
  132.         private static void Send(Socket handler, string data)
  133.         {
  134.             // Convert the data string to byte data using ASCII encoding
  135.             byte[] byteData = Encoding.ASCII.GetBytes(data);
  136.  
  137.             // Starts sending data to the remote device
  138.             handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
  139.         }
  140.  
  141.         private static void SendCallback(IAsyncResult ar)
  142.         {
  143.             try
  144.             {
  145.                 // Get object state socket
  146.                 Socket handler = (Socket)ar.AsyncState;
  147.  
  148.                 // Finish sending data to the remote device
  149.                 int bytesSent = handler.EndSend(ar);
  150.                 Console.WriteLine("Send {0} bytes to client.", bytesSent);
  151.  
  152.                 handler.Shutdown(SocketShutdown.Both);
  153.                 handler.Close();
  154.             }
  155.             catch (Exception e)
  156.             {
  157.                 Console.WriteLine(e.ToString());
  158.             }
  159.         }
  160.  
  161.         public static int Main(string[] args)
  162.         {
  163.             StartListening();
  164.             return 0;
  165.         }
  166.     }
  167. }
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