Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to handle a client connection (socket programming)

For every single tutorials and examples I have seen on the internet for Linux/Unix socket tutorials, the server side code always involves an infinite loop that checks for client connection every single time. Example:

http://www.thegeekstuff.com/2011/12/c-socket-programming/

http://tldp.org/LDP/LG/issue74/tougher.html#3.2

Is there a more efficient way to structure the server side code so that it does not involve an infinite loop, or code the infinite loop in a way that it will take up less system resource?

like image 879
leorex Avatar asked Jul 27 '12 11:07

leorex


People also ask

How do you handle multiple clients in socket programming?

A better way to handle multiple clients is by using select() linux command. Select command allows to monitor multiple file descriptors, waiting until one of the file descriptors become active. For example, if there is some data to be read on one of the sockets select will provide that information.

What are the techniques for working with socket programming?

In the client-side socket program, we need to make a socket object. Then we will connect to the port on which our server is running — 12345 in our example. After that we will establish a connection by using the socket. connect() method.

Which programming language is best for socket programming?

Socket Programming in C/C++

How do you handle multiple clients in socket programming in Java?

The method printToALLClients() sends the output to each client in the thread. For the Client, we use the Socket class and initiate the connection to a server bypassing the IP address and port number. We use the Scanner to get the input from the user and send the data to the server using the PrintWriter object.


1 Answers

the infinite loop in those examples is already efficient. the call to accept() is a blocking call: the function does not return until there is a client connecting to the server. code execution for the thread which called the accept() function is halted, and does not take any processing power.

think of accept() as a call to join() or like a wait on a mutex/lock/semaphore.

of course, there are many other ways to handle incoming connection, but those other ways deal with the blocking nature of accept(). this function is difficult to cancel, so there exists non-blocking alternatives which will allow the server to perform other actions while waiting for an incoming connection. one such alternative is using select(). other alternatives are less portable as they involve low-level operating system calls to signal the connection through a callback function, an event or any other asynchronous mechanism handled by the operating system...

like image 51
Adrien Plisson Avatar answered Sep 29 '22 10:09

Adrien Plisson