Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- using System.Threading;
- namespace Comm_Distance
- {
- // Object state for asynchronous reading of Client data
- public class StateObject
- {
- // Socket client
- public Socket workSocket = null;
- // Buffer size
- public const int BufferSize = 1024;
- // Buffer reception
- public byte[] buffer = new byte[BufferSize];
- // Reception data string
- public StringBuilder sb = new StringBuilder();
- }
- public class AsynchronousSocketListener
- {
- // Thread signal
- public static ManualResetEvent allDone = new ManualResetEvent(false);
- public AsynchronousSocketListener()
- {
- }
- public static void StartListening()
- {
- /* Establish local endpoint for socket
- Device DNS is running listener
- which is "192.168.56.1"
- */
- IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
- IPAddress ipAddress = ipHostInfo.AddressList[0];
- IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
- // TCP / IP socket creation
- Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
- // Bind the socket to the local endpoint and listen for incoming connections
- try
- {
- listener.Bind(localEndPoint);
- listener.Listen(100);
- while (true)
- {
- // Set the event to an unreported state
- allDone.Reset();
- // Start asynchronous socket to listen for connections
- Console.WriteLine("Waiting for a connection...");
- listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
- // Wait for a connection to be established before continuing
- allDone.WaitOne();
- }
- }
- catch (Exception e)
- {
- Console.WriteLine(e.ToString());
- }
- Console.WriteLine("\nPress ENTER to continue...");
- Console.Read();
- }
- public static void AcceptCallback(IAsyncResult ar)
- {
- // Signal to the main thread to continue
- allDone.Set();
- // Gets the socket that handles the client request
- Socket listener = (Socket)ar.AsyncState;
- Socket handler = listener.EndAccept(ar);
- // Create Object state
- StateObject state = new StateObject();
- state.workSocket = handler;
- handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
- }
- public static void ReadCallback(IAsyncResult ar)
- {
- string content = string.Empty;
- /*Get status object and manager socket
- * from the asynchronous state object
- */
- StateObject state = (StateObject)ar.AsyncState;
- Socket handler = state.workSocket;
- // Read the data from the client socket
- int bytesRead = handler.EndReceive(ar);
- if (bytesRead > 0)
- {
- // If there is more data, then we store the data received so far
- state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
- // Checks the end of file tag. If it's not good, read more data
- content = state.sb.ToString();
- if (content.IndexOf("<EOF>") > -1)
- {
- /* All data has been read from the client
- Display on the console
- */
- Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content);
- // Return data to client
- Send(handler, content);
- }
- else
- {
- // If all the data have not been received. Take more.
- handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback),
- state);
- }
- }
- }
- private static void Send(Socket handler, string data)
- {
- // Convert the data string to byte data using ASCII encoding
- byte[] byteData = Encoding.ASCII.GetBytes(data);
- // Starts sending data to the remote device
- handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
- }
- private static void SendCallback(IAsyncResult ar)
- {
- try
- {
- // Get object state socket
- Socket handler = (Socket)ar.AsyncState;
- // Finish sending data to the remote device
- int bytesSent = handler.EndSend(ar);
- Console.WriteLine("Send {0} bytes to client.", bytesSent);
- handler.Shutdown(SocketShutdown.Both);
- handler.Close();
- }
- catch (Exception e)
- {
- Console.WriteLine(e.ToString());
- }
- }
- public static int Main(string[] args)
- {
- StartListening();
- return 0;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement