How can I create a simple server with only 2 clients in C++? - 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.

Related

Do a server block execution when listening for client connection?

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.

How to use waitformultipleobject in C++

I am trying to write a code that will wait for client connections. As soon as it gets connected to a client, it should start reading a file and send it.
I need to have notifications for the socket handles, that is if connection gets lost from client side it will notify me so that I can try to reconnect.
If a connection is lost, it is up to the client side to reconnect. Servers do not connect or reconnect to clients.
If your server is simply dispensing a file, all you need to do is to accept connections and pass them to a handler that will invoke TransmitFile() at some point and clean up.
I am assuming the parts about waiting for client connections and sending a file are just for clarification and you already got that working. If not, there are lots of tutorials on sockets and file I/O out there.
In your case, detecting whether or not a client is still connected should be simple. Since your server is sending a file as soon as the connection is made, the client will start reading from the socket as soon as it is open. The read-function blocks, as long as the connection is open and no data was received. If the connection is closed, it will return having read 0 bytes. At that point you know, that the connection was terminated and you can try to reconnect.
If you are not permanently reading from the socket but keeping it open for future communication, you should look into the select-function, which allows monitoring one or more sockets and notifies you, as soon as one of them has an update (for example new data available or connection closed)

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.

C++ socket concurrent server

I'm writing a concurrent server that's supposed to have a communication channel and a data channel.
The client initially connects to the communication channel to authenticate, upon successful authentication, the client is then connected to the data channel to access data.
My program is already doing that, and I'm using threads. My only issue is that if I try to connect another client, I get a "cannot bind : address already in use" error.
I have it this way:
PART A
Client connects to port 4567 (and enters his login info). A thread is spawned to handle the client (repeated for each client that connects). In the thread created, I have a function (let's call it FUNC_A) that checks the client's login info (don't worry about how the check is done), if successful, the thread starts the data server (listening on 8976), then sends an OK to the client, once received the client attempts to connect to the data server.
PART B
Once a client connects to the data server, from inside FUNC_A the client is accepted and another thread is spawned to handle the client's connection to the data server (hopefully everything is clear).
Now, all that is working fine. However, if I try to connect with second client when it gets to PART B I get a "cannot bind error: address already in use". I've tried so many different ways, I've even tried spawning a thread to start the data server and accept the client and then start another thread to handle that connection. Still no luck.
Please give me a suggestion as to what I'm doing wrong, how do I go about doing this or what's the best way to implement it.
Thank you
Your problem lies in the following: "...the thread starts the data server(listening on 8976)..."
If I understand you correctly, every time a client connects, you're trying to start listening on port 8976. The problem is, however, that there can be only one socket listening on a given port. When you try to start listening on the same port again, you get that error.
Therefore, you have two options:
Have the server listen on whatever port is free (just specify 0 when binding), and send the port number to the client, so that the client can connect to it.
Start the server only once, at the beginning, and have it accept client connections.
The second option, however, has a big problem: how are you going to tell one client from another? Therefore, I recommend going with the first option.
Some food for thought: what you're describing is pretty much exactly how FTP works. And FTP servers use the first option. Not coincidentally, perhaps? ;-)

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.)