Do a server block execution when listening for client connection? - c++

I'm new to socket programming and I want to create a client/server type of application using winapi. I want my application to be listening for a request from a client, and after serving the client it should continue listening for further requests. But before making an attempt I what to get an overview for understanding of the whole process. My question is when you call listen() on the server side, does the listen() block executes until a client tries to make a connection?
and after accepting and serving the current client, how does it get back to listening mode for other connections? because from the code I saw on the sites I visited there is no loop which calls listen() again after serving a client, it goes straight to close().
Please forgive me for not adding any code because I want to get basic knowledge before I can attempt it my self.

From the diagram as you can see doesn't block on listen()
Also, this link might help you.
From the block you can which are blocking calls

when you call listen() on the server side, does the listen() block executes until a client tries to make a connection?
No. listen() simply opens the listening port and establishes the backlog to hold pending connections, and then it exits. It is accept() instead that blocks waiting for a connection (if you use it in blocking mode, that is, which is the default).
after accepting and serving the current client, how does it get back to listening mode for other connections?
It is up to you to decide when that happens. The server will not go back to listening for a connection until you call accept() again. So you need to call accept() in a loop for the lifetime of your server. But, your server design will dictate WHEN you call accept().
If you want to service only 1 client at a time, then you simply have 1 loop that calls accept(), services the client in full, closes the accepted socket, and goes back to accept().
But, if you want to service multiple clients in parallel, then you need to accept clients as often as possible, either by calling accept() in a dedicated thread or select() loop, or by using AcceptEx() in the background by Overlapped I/O or an I/O Completion Port. Once a client has been accepted, you need to then decide whether you want to service the client directly in your select() loop, or in its own dedicated thread, or with Overlapped I/O or IOCP.
from the code I saw on the sites I visited there is no loop which calls listen() again after serving a client, it goes straight to close().
No, there is never a listen() loop. listen() is only to be called once, when opening the server port. But you do need an accept() loop instead to accept clients.
Please forgive me for not adding any code because I want to get basic knowledge before I can attempt it my self.
Literally, there are TONS of socket tutorals available online, and detailed WinSock documentation and examples on MSDN. All of them cover this topic.

Related

Does listen() run continuously or do I need to loop it to keep receiving connections on a socket?

I'm running a client and server on the same machine using a loopback address for learning purposes yet my "server" code seems to fly back listen() and then hangs on my connect(). Does listen() need to be in an endless loop to keep receiving connections?
How would I determine a connection is made/in the queue if listen() returns 0 even when I haven't made a connection yet?
I have an accept() call following but the code hangs on that spot. I have debug statements right before and after and it never gets past the accept().
On the other end my client code seems to connect() just fine (doesn't throw an error) and appears to write and complete even though the server code never gets the connection.
The listen function defines the backlog. Only need to call this once.
Then use accept to receive an incoming connection. Best to deal with this promptly and go around again for another accept.
Both connect() and accept() should block while waiting for a connection.
connect() #client blocks while waiting for remote server to answer
accept() #server blocks while waiting for a client
listen() should not block at all. It tells the OS to allocate additional memory for requests, so that the OS can queue clients who arrive at the same time. You only need to call it once.
If accept() never completes in the server, then you most likely never have a connection. If the connect() call is completing in your client, then you need to check its return value. If it returns with a -1, then the connection failed. It sounds like this is most likely what is happening. You can still write to a socket without a connection, but your message will not go anywhere.

How to close boost asio server socket with all client sockets connected

I use boost:asio::ip::tcp::acceptor to create server socket in my app. I close this acceptor socket using close function, than stop function in io_service but all connected client sockets closes only when my app is closed. How can i fix that?
Thanks!
Do either of the following:
invoke socket::close() on the sockets.
destroy the socket. See this answer for details on how the socket will be closed during destruction.
io_service::stop() only stops processing of the event loop. Work can still be posted into the io_service, and existing work will remain in the io_service. Thus, the application must call socket::close() on each of the sockets it wishes to close. For a portable graceful closure, call socket::shutdown() before calling close().
It may be worth taking the time to review Boost.Asio's HTTP Server 1 example. It uses a connection_manager to shutdown all connections.

Multiple connections on the same port socket C++

I need to accept multiple connections to the same port.
I'm using socket in C++, i want to do something like the SSH do.
I can do an ssh user#machine "ls -lathrR /" and run another command to the same machine, even if the first one still running.
How can i do that?
Thanks.
What you want is a multithreaded socket server.
For this, you need a main thread that opens up a socket to listen to (and waits for incoming client connections). This has to go into a while loop of some sort.
Then, when a client connects to it, the accept() function will unblock and at that point you need to serve the client request by passing on the request to a thread that will deal with it.
The server side will loop back and wait for another connection whilst the previous thread carries on its task.
You can either create threads as you need, or use a thread pool which might be more efficient (saving on time initialising new threads).
Have a look here for some more details.
Look for multithreaded server socket on the web, specifically bind(), listen() and accept() from the server side.
You need to read up on ::listen() and ::accept().
The former will set up your socket for listening. You then need a loop (probably in its own thread) which uses ::accept() which will return each time a new connection arrives.
That loop should then spawn a new thread to which you should pass the file descriptor received from ::accept() and then handles all I/O on that socket from thereon.
Old question is old, but I feel no one who answered understood the OP's question.
You're misunderstanding how ssh works. When you send multiple commands/multiple connections to a server over ssh, there is actually only ONE program on the server you're connecting to that is receiving all those commands.
Sshd (the ssh daemon) runs on the server, and is a multithreaded socket server (see fduff's answer). This is the only program that listens on port 22, and handles all incoming ssh connections by itself.

How can I create a simple server with only 2 clients in C++?

I need to create a server that allow ONE at time client connected.
The rule is that just one client can be connected and if the other one try to connect, can read a messagge like this "another client is connected, do you want disconnect it?".
Then if type yes the client will be disconnected.
My problem is about this step. How can I disconnect a client and connect the other one?
Can someone help me?
Thank you.
First build the abstract server structure. So you write a program which accepts TCP connections in one thread and pass them to a worker thread, which can read and send messages.
You should keep one Singleton containing a reference (or pointer, your choice) to the Worker with the currently connected client (or null, if there is noone connected).
To keep it simple, the acceptor thread should create a new Worker thread everytime it accepts a connection, and the Worker thread is terminated, when the connection breaks up.
Now you have to think about a protocol. For this simple task, 5 messages should be enough. Maybe every message ends with an endl, so you can use methods like readline if there is somthing like this in C++.
First, the CONNECT message. The server should return OK (second message), if noone is connected to it, and ERROR (third message), if there is already one connected.
The fourth message is CONNECTWITHDISCONNECT, it connects the client to the server and disconnects any other client. The newly connected client should receive a OK message from the server, and the disconnected one should receive DISCONNECT (fifth message).
Now, you could use the disconnect message also with the client, so one can disconnect, without requiring another to connect.
The client should send a CONNECT first, if it receives ERROR then, it can ask the user to disconnect the other client, and if the user wants to, the client sends CONNECTWITHDISCONNECT.
Another option (if you don't want to deal with multiple threads or multiple processes) is to use select() or poll() to handle multiple sockets at the same time within a single thread. In particular, you can select()-for-read on your accepting socket, and select() will return with that socket marked as ready-for-read whenever another client is trying to connect. Once you have accept()'d the client, you can pass the client's connection socket (as was returned by accept()) to select()'s read-sockets-set so that you will also be notified whenever the client's socket has bytes ready for you to read. And so on.

Multithreaded Server Issue

I am writing a server in linux that is supposed to serve an API.
Initially, I wanted to make it Multi-threaded on a single port, meaning that I'd have multiple threads working on various request received on a single port.
One of my friends told me that it not the way it is supposed to work. He told me that when a request is received, I first have to follow a Handshake procedure, create a thread that is listening to some other port dedicated to the request and then redirect the requested client to the new port.
Theoretically, it's very interesting but I could not find any information on how to implement the handshake and do the redirection. Can someone help?
If I'm not wrong in interpreting your responses, once I create a multithreaded server with a main thread listening to a port, and creates a new thread to handle requests, I'm essentially making it multithreaded on a single port?
Consider the scenario where I get a large number of requests every second. Isn't it true that every request on the port should now wait for the "current" request to complete? If not, how would the communication still be done: Say a browser sends a request, so the thread handling this has to first listen to the port, block it, process it, respond and then unblock it.
By this, eventhough I'm having "multithreads" , all I'm using is one single thread at a time apart from the main thread because the port is being blocked.
What your friend told you is similar to passive FTP - a client tells the server that it needs a connection, the server sends back the port number and the client creates a data connection to that port.
But all you wanted to do is a multithreaded server. All you need is one server socket listening and accepting connections on a given port. As soon as the automatic TCP handshake is finished, you'll get a new socket from the accept function - that socket will be used for communication with the client that has just connected. So now you only have to create a new thread, passing that client socket to the thread function. In your server thread, you will then call accept again in order to accept another connection.
TCP/IP does the handshake, if you can't think of any reason to do a handshake than your application does not demand it.
An example of an application specific handshake could be for user authentication.
What your colleague is suggesting sounds like the way FTP works. This is not a good thing to do -- the internet these days is more or less used for protocols which use a single port, and having a command port is bad. One of the reasons is because statefull firewalls aren't designed for multi-port applications; they have to be extended for each individual application that does things this way.
Look at ASIO's tutorial on async TCP. There one part accept connections on TCP and spawns handlers that each communicate with a single client. That's how TCP-servers usually work (including HTTP/web, the most common tcp protocol.)
You may disregard the asynchronous stuff of ASIO if you're set on creating a thread per connection. It doesn't apply to your question. (Going fully async and have one worker-thread per core is nice, but it might not integrate well with the rest of your environment.)