namespace NetworkTester { public class Program { static OutputPort led = new OutputPort(Pins.ONBOARD_LED, false); public static byte[] StrToByteArray(string str) { System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); return encoding.GetBytes(str); } public static void Main() { // write your code here NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface networkInterface in networkInterfaces) { networkInterface.EnableStaticIP("192.168.1.36", "255.255.255.0", "192.168.1.1"); Debug.Print("Gateway Address: " + networkInterface.GatewayAddress); Debug.Print("IP Address: " + networkInterface.IPAddress); Debug.Print("Subnet mask " + networkInterface.SubnetMask); } using (System.Net.Sockets.Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Any, 80)); Debug.Print("first"); socket.Listen(1); Debug.Print("here"); while (true) { using (Socket commSocket = socket.Accept()) { Debug.Print("here1"); commSocket.Send(StrToByteArray("\r\n" + "Hello")); bool stay = true; while (stay) { if (commSocket.Poll(-1, SelectMode.SelectRead)) { Debug.Print("here2"); byte[] bytes = new byte[commSocket.Available]; int count = commSocket.Receive(bytes); string s = new String(Encoding.UTF8.GetChars(bytes)); if (s == "c") { commSocket.Send(StrToByteArray("\r\n" + "Good Night!")); stay = false; } if (s == "l") { led.Write(true); // turn on the LED Thread.Sleep(100); // sleep for 250ms led.Write(false); // turn on the LED } if (s == "o") { led.Write(false); // turn on the LED Thread.Sleep(100); // sleep for 250ms led.Write(true); // turn on the LED } Debug.Print(s); } } Debug.Print("done"); } } } } } }
Here is what I would like to do next:
1. I would like to accept multiple clients at the same time. Anyone have thoughts about how do do that?
2. Right now this gets hung up if one of the clients exits unexpectedly. How can I gracefully detect that a client went away?