My objective:
1. Open socket connection with Socket clientSocket = socket.Accept()
2. Listen, read data, send data,
3. Check if socket is still open
4. If yes, continue listening, if no go back to step 1
This needs to be reliable so that if the PC program is closed or terminated, it should be able to restart and resume sending and receiving messages
My issue:
1. I have to run a double loop, if the inside loop is taken out, the client(PC)/server(Netduino Plus) exchange 1 set of messages, then the client receives around 18 blank messages, then I get an error "Unable to write data to the transport connection: An established connection was aborted by the software in your host machine."
Same error happens if I stop the program on the PC and restart it again.
2. I cannot find a method to check if the socket is still connected. I read that in .Net framework, there is a method System.Net.Sockets.Connected(), but it's missing in the .Net Micro framework. I tried using .Available, but this method just seems to check how much data is available in the buffer, doesn't check if the socket is open
Can someone help me verify that I am doing this correctly,
Server (Netduino Plus) code
public WebServer() { Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].EnableDhcp(); //Initialize Socket class Thread.Sleep(2000); socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //Request and bind to an IP from DHCP server socket.Bind(new IPEndPoint(IPAddress.Any, 80)); //Debug print our IP address Debug.Print(Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].IPAddress); //Start listen for web requests socket.Listen(10); ListenForRequest(); } public void ListenForRequest() { while (true) { using (Socket clientSocket = socket.Accept()) { //while (clientSocket.Available == 0) //Must have this if sending repeated messages while(sw.Read() == true) { //Get clients IP IPEndPoint clientIP = clientSocket.RemoteEndPoint as IPEndPoint; EndPoint clientEndPoint = clientSocket.RemoteEndPoint; //int byteCount = cSocket.Available; int bytesReceived = clientSocket.Available; if (bytesReceived > 0) { //Get request byte[] buffer = new byte[bytesReceived]; int byteCount = clientSocket.Receive(buffer, bytesReceived, SocketFlags.None); string request = new string(Encoding.UTF8.GetChars(buffer)); Debug.Print(request); //Compose a response string response = "Hello World"; string header = "HTTP/1.0 200 OK\r\nContent-Type: text; charset=utf-8\r\nContent-Length: " + response.Length.ToString() + "\r\nConnection: close\r\n\r\n"; clientSocket.Send(Encoding.UTF8.GetBytes(header), header.Length, SocketFlags.None); clientSocket.Send(Encoding.UTF8.GetBytes(response), response.Length, SocketFlags.None); //Blink the onboard LED //led.Write(true); Thread.Sleep(150); //led.Write(false); } } } } }
Client (PC) code
byte[] data = new byte[1024]; string input, stringData; TcpClient server; try { server = new TcpClient("169.254.226.240", 80); } catch (SocketException) { label1.Text = "Unable to connect to server"; return; } NetworkStream clientStream = server.GetStream(); ASCIIEncoding encoder = new ASCIIEncoding(); byte[] buffer = encoder.GetBytes("Hello Client!"); while (true) { if (clientStream.CanWrite) { clientStream.Write(buffer, 0, buffer.Length); clientStream.Flush(); } if (clientStream.CanRead) { byte[] myReadBuffer = new byte[1024]; StringBuilder myCompleteMessage = new StringBuilder(); int numberOfBytesRead = 0; // Incoming message may be larger than the buffer size. do { numberOfBytesRead = clientStream.Read(myReadBuffer, 0, myReadBuffer.Length); myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead)); } while (clientStream.DataAvailable); // Print out the received message to the console. Console.WriteLine("You received the following message : " + myCompleteMessage); } Thread.Sleep(1000); //break; }