Click here to Skip to main content
15,895,709 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi Guys,
I have a question regarding TCP Listeners and Clients that probably doesn't have one answer but i thought i would post it anyway to see what people think.

Project Description:
I have recently started playing around with the Arduino Hardware, in particular the Ethernet Sheild. I was thinking about making an IP Temperature Sensor that would connect to a PC running a TCP Listener and send a data string containing the current temperature every minute.

Question:
Is it better to keep a TCP connection to a server permantly alive or connect to the TCP Listener, send the command and then terminate the connection every time i wish to communicate something?


Code:
The Code below seems to be able to connect and communicate with the arduino.
try
{
    /// Local IP Address.
    IPAddress ip = IPAddress.Parse("127.0.0.1");
    /// Initializes the Listener.
    TcpListener myListener = new TcpListener(ip, 8001);
    /// Start Listeneting at the specified port.
    myListener.Start();
    listbox1.Items.Add("The Listener is running on " + myListener.LocalEndpoint);
    listbox1.Items.Add("Waiting for a connection...");
    Socket mySocket = myListener.AcceptSocket();
    listbox1.Items.Add("Connection accepted from " + mySocket.RemoteEndPoint);

    /// Receives Message From Client.
    byte[] rData = new byte[100];
    int k = mySocket.Receive(rData);
    listbox1.Items.Add("Recieved...");
    for (int i = 0; i < k; i++)
        listbox1.Items.Add(Convert.ToChar(rData[i]));
    ASCIIEncoding tData = new ASCIIEncoding();
    mySocket.Send(tData.GetBytes("response"));
    listbox1.Items.Add("\nSent Response");

    /// Close Connection.
    mySocket.Close();
    myListener.Stop();
}

catch
{
    listbox1.Items.Add("You broke something...");
}


More Information:
On the Arduino side of things i am just using the default "Web Client" example that comes with the arduino-0018 software and changed the IP address and port.

Thanks in advance,
Alex.
Posted

1 solution

Well, it's pretty much up the client to break the connection, but if you wanted to force the issue, you could break it on the server side. It's really a matter of what you prefer. If you wrote the client code as well, I think it would be better to have the client send the info and then break the connection. The listener on the server will reset itself (or should), and wait for the next connection.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900