public static void StartListening() { kern.etc.Config config = new etc.Config(); // Establish the local endpoint for the socket. // The DNS name of the computer // running the listener is "host.contoso.com". string ip = config.BASE_IP(); int port = config.BASE_PORT(); System.Net.IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); System.Net.IPAddress ipAddress = ipHostInfo.AddressList[0]; System.Net.IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port); // Create a TCP/IP socket. 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 nonsignaled state. allDone.Reset(); // Start an asynchronous socket to listen for connections. Console.WriteLine("Waiting for a connection..."); listener.BeginAccept( new AsyncCallback(AcceptCallback), listener); // Wait until a connection is made before continuing. allDone.WaitOne(); } } catch (Exception e) { Console.WriteLine(e.ToString()); } Console.WriteLine("\nPress ENTER to continue..."); Console.Read(); }
public static void OpenSocket(string host, int port, string data) { // Connect to a remote device. try { // Establish the remote endpoint for the socket. // The name of the // remote device is "host.contoso.com". IPHostEntry ipHostInfo = Dns.GetHostEntry(host); IPAddress ipAddress = ipHostInfo.AddressList[0]; IPEndPoint remoteEP = new IPEndPoint(ipAddress, port); // Create a TCP/IP socket. System.Net.Sockets.Socket client = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); // Connect to the remote endpoint. client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client); connectDone.WaitOne(); etc.Config configdata = new etc.Config(); // Send test data to the remote device. string datastream = data + "<EOF>"; Send(client, datastream); sendDone.WaitOne(); // Receive the response from the remote device. Receive(client); receiveDone.WaitOne(); // Write the response to the console. Console.WriteLine("Response received : {0}", response); // Release the socket. client.Shutdown(SocketShutdown.Both); client.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()); } }