Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 465
user334258 Avatar asked Oct 25 '22 15:10

user334258


1 Answers

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:

  1. 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.
  2. 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? ;-)

like image 134
Fyodor Soikin Avatar answered Nov 15 '22 06:11

Fyodor Soikin