Reputation: 31
I'm following the tutorial (big code block near the bottom of that section) here:http://beej.us/guide/bgnet/output/html/multipage/advanced.html#select And the main server code code is like so:
while (true)
{
read_fds = master;
if (select(fd_max + 1, &read_fds, NULL, NULL, NULL) == -1)
{
cerr << "ERROR. Select failed" << endl;
return -1;
}
for (int i = 0; i <= fd_max; i++)
{
if (FD_ISSET(i, &read_fds))
{
if (i == welcome_socket)
{
cout << "NEW CONNECTION" << endl;
client_len = sizeof(struct sockaddr_in);
client_sock = accept(welcome_socket, (struct sockaddr *) &client_addr, &client_len);
if (client_sock != -1)
{
FD_SET(client_sock, &master);
if (client_sock > fd_max)
{
fd_max = client_sock;
}
}
}
else
{
int length, total_read = 0;
// CONNECTION CLOSED BY CLIENT
if (safe_recv(client_sock, &length, sizeof(int)) <= 0)
{
cout << "CONNECTION CLOSED" << endl;
close(i);
FD_CLR(i, &master);
}
else
{
char *message = (char *)memset((char *)malloc(length + 1), 0, length);
// while ((total_read += safe_recv(client_sock, message + total_read, length - total_read)) < length) {}
safe_recv(client_sock, message, length);
// RESPOND WITH MESSAGE
cout << "MESSAGE: " << message << endl;
write(client_sock, process(message), length);
free(message);
}
}
}
}
}
What I'm doing is first sending (from the client) the length of the string, then the string itself. Then the server sends back process(message)
.
When I only have 1 connection, I'm seeing correct behaviour. However if 1 is connected already and I connect a new client, what I'm seeing is:
CONNECTION CLOSED
twice)I've tried to keep this very similar to the tutorial code. I've run the tutorial server, and that works as intended with several clients. I'm new to network programming, so I apologise if this is a beginner problem or just something dumb I overlooked.
Upvotes: 0
Views: 62
Reputation: 33931
The code reads from and writes to only client_sock
, and client_sock
is replaced with the new socket in the accept handling portion of the code.
Most likely you want to interact with i
rather than client_sock
.
Upvotes: 1