network->SocketHandler.hpp
SocketHandler
designed to handle multiple connections to the clients. It can accept
connections, send/receive messages to them, ...
This class have a member called 'update'. 'update' will call every time
simulator needs to get messages or accept new connections.
Author: Aidin Gharibnavaz
Constructors |
SocketHandler(int max,int port)
Create a server socket on 'port' which accept 'max' number of connections.
Methods |
vector<MessageStruct>
update()
Check for the new connections
pending, and get messages that sent by robots. Return messages in a
Linked List format. (See LinkedList class).
If any new connection received, it
will call 'acceptIncomingConnection' method in this class.
int
sendMessage(int
ID, std::string
message)
Send 'message' to the robot with 'ID' id.
Private Methods |
void
acceptIncomingConnection()
This method will accept a new
connection pending. It's a private member and will called by
'update'.
How it works? |
Constructor will create a server socket which can accept connections coming from clients. Details of how it done doesn't matter. You can find information about this on the web sites.
Then it comes to the 'update()'. I used 'select()' function to check whether a message comes or a new connection pending. 'select()' will check it for us and put the result in a 'set'. It need the maximum file descriptor available. So we have two private variable: maxFileDescriptor & clientsSet. 'maxFileDescriptor' will hold maximum file descriptor of the sockets until now. 'clientSet' is a set of descriptors of the clients.
First it will check for new connections. If any, it will call 'acceptIncomingConnection()'. Then a loop will started: check if the first client sent any message, if any, it will store it on the 'result' variable. If any clients disconnected, it will remove it from the 'set'. Then, check for the next client and so on. At the end, it will return 'result', which now contains messages just received.
Why we use 'select()'?
When a process call 'recv' (for reading message from socket), the operating system will block it until socket become ready for reading. It mean the process should wait until someone send something to the socket. And if no one do this? it will remain blocked forever. 'select()' function check if the socket is ready for reading or not. In this way, our program haven't to wait for a certain client.