I\'m trying to make a server that can be connected to by multiple clients. Here\'s my code so far:
Client:
int main(int argc, char **argv) {
struct so
1) It is a good practice to use PF_INET(protocol family) rather than
AF_INET(address family) during the Socket creation .
2) within the while(1) loop
each time it is advisable to make your readfds empty by using FD_ZERO(&readfds).
in the recv() call you should use i rather than clientsocks[i]
you have to check return value of recv is negative(which indicating error in reading) if that is the case you do not have to print the message.
during printing the message make sure the stdout/server is ready for writing anything to it which you can do it by using writefds (3rd argument of select).
You need to check for limit <= 0 in your read loop, before you call read.
In the while loop for the server, change the code to do recv(i)
instead of recv(clientsocks[i])
. I have implemented this code and it works with this change.
Two issues in your code:
You should do recv(i, ...)
instead of recv(clientsock[i], ...)
After that you do not check if recv()
failed, and therefore printf()
prints out the uninitialised buffer message
, hence the garbage in the output
I replaced the else with the below and it works
} else {
/* int messageLength = 5;
char message[messageLength+1];
int in, index = 0, limit = messageLength+1;
memset ( &message[index] , 0, sizeof ( message [index] ) );
while ((in = recv(i, &message[index], limit, 0)) > 0) {
index += in;
limit -= in;
}
printf("%d\n", index);
printf("%s\n", message);
*/
bzero(buf, sizeof(buf));
if ((rval = read(i, buf, 1024)) < 0)
perror("reading stream message");
else if (rval == 0)
printf("Ending connection\n");
else
printf("-->%s\n", buf);
}