I used a photon to test the socket function,when the first client connect to the server ,it can send(receive) the data to(from) the server.But after the second client connect to it,both clients could not send and get data.I want to know if there is some functions to stop another client to connect to the server after the first one is connected?
You might be able to configure your server to only support 1 client?
I just don’t want another client to block me when I was connecting to the server.Are there any good advices?
Your server will then have to handle the connections are serve them accordingly? I’m not an expert in server/client but that’s what i would do if i need to code one instead of having it not responding the server gets multiple connection
The TCPServer does support multiple client sockets, but not in the way it’s described in the docs. The server.write() method does not write to all connected clients, it actually writes to the last connected client.
What you need to do is:
In your loop, when you call server.available() you don’t store the TCPClient object in a global variable. You need to have some sort of array/list/whatever to hold the multiple clients you wish to support. If the client returned by server.available() then has client.connected() true, that means a new connection was established, and you should handle data on that connection.
In loop(), you will need to loop through all active connections, and do the reads and writes as you need to for your application. Make sure you use client.write() to write to that client, not server.write(), which doesn’t work right for multiple clients.
If client.connected() returns false on a previously active connection, the other side has disconnected and you should handle orderly shutdown of that connection and add it back into your free pool/mark as not active.
Also, you need to continue to call server.available() as above, even when you have connections, so new connections come in, unlike the example server code.
It worked !! Thanks for your good suggestion !!
I’m implementing this solution right now, and I’m curious as to what data structure you ended up using. I haven’t been in C/C++ land since college, so I’m not sure what the standard linked list data structure is for Photon/Arduino projects. Thanks for the help!
Here’s an example of a TCP server that allows multiple connections. It’s actually a tiny HTTP server, but it only serves a single file. The important part is that it shows how to handle multiple connections, which is kind of confusing.
Oh, fantastic! Thanks for that example, that’d work well for our use case as well.