Need help determining if socket connection exists - Netduino Plus 2 (and Netduino Plus 1) - Netduino Forums
   
Netduino home hardware projects downloads community

Jump to content


The Netduino forums have been replaced by new forums at community.wildernesslabs.co. This site has been preserved for archival purposes only and the ability to make new accounts or posts has been turned off.
Photo

Need help determining if socket connection exists


  • Please log in to reply
1 reply to this topic

#1 kennethone

kennethone

    New Member

  • Members
  • Pip
  • 4 posts

Posted 04 September 2012 - 08:19 PM

Good afternoon,

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;
            }


#2 Cuno

Cuno

    Advanced Member

  • Members
  • PipPipPip
  • 144 posts
  • LocationZürich / Switzerland

Posted 05 September 2012 - 08:50 AM

I cannot find a method to check if the socket is still connected.

This is a common misconception about TCP/IP. You cannot determine whether a TCP connection still exists, except by trying to send data over this connection.

See e.g. this blog posting.

The "Connected" property in the full .NET framework only means "if Connected is false, then the connection is not open". The opposite is not true! "Connected is true" has very little semantics, it just means "the last operation was successful, we don't know anything about the current state of the connection". Thus this property is very asymmetric: you only know anything for sure if it is false, you don't know anything useful if it is true.

So if you want to be notified of a closed connection after at most t seconds, then you need to implement some kind of "heart beat" protocol in your application that writes over the connection every t seconds.

Best regards

Cuno




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

home    hardware    projects    downloads    community    where to buy    contact Copyright © 2016 Wilderness Labs Inc.  |  Legal   |   CC BY-SA
This webpage is licensed under a Creative Commons Attribution-ShareAlike License.