Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accept multiple subsequent connections to socket

Tags:

c

sockets

I have a listener that will pass arbitrary data, HTTP requests, to a network socket which is then delivered over TCP. This works fine for the first request but the listener does not accept subsequent new requests.

My question is:

If I have sock=accept(listener,(struct addr *)&sin, &sinlen); then, based on the socket function reference, the listener socket remains open and I should be able to re-call accept() any number of times for subsequent requests. Is this correct? If so, can someone more familiar than I with socket programming please explain how this code might look?

like image 616
Tok Avatar asked Mar 22 '11 14:03

Tok


People also ask

How do you handle multiple connections in a socket?

Create a temporary SOCKET object called ClientSocket for accepting connections from clients. Normally a server application would be designed to listen for connections from multiple clients. For high-performance servers, multiple threads are commonly used to handle the multiple client connections.

What is the use of accept in socket programming?

The accept () call is used by a server to accept a connection request from a client. When a connection is available, the socket created is ready for use to read data from the process that requested the connection. The call accepts the first connection on its queue of pending connections for the given socket socket.

What happens when a server accepts a client socket?

When the client connection has been accepted, a server application would normally pass the accepted client socket (the ClientSocket variable in the above sample code) to a worker thread or an I/O completion port and continue accepting additional connections. In this basic example, the server continues to the next step.

What happens when a socket connection is made?

When a connection is available, the socket created is ready for use to read data from the process that requested the connection. The call accepts the first connection on its queue of pending connections for the given socket socket. The accept () call creates a new socket descriptor with the same properties as socket and returns it to the caller.


1 Answers

Yes, you can accept() many times on the listening socket. To service multiple clients, you need to avoid blocking I/O -- i.e., you can't just read from the socket and block until data comes in. There are two approaches: you can service each client in its own thread (or its own process, by using fork() on UNIX systems), or you can use select(). The select() function is a way of checking whether data is available on any of a group of file descriptors. It's available on both UNIX and Windows.

like image 147
Ernest Friedman-Hill Avatar answered Nov 15 '22 07:11

Ernest Friedman-Hill