Reputation: 53
I'm writing in C and creating a Server that receives connections from multiple different Clients one at a time. However, after the first connection closes, the server can't be connected to again.
server.c:
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <unistd.h>
int main() {
while(1) {
char server_message[256] = "You have reached the server!";
//Create a socket
int server_socket;
server_socket = socket(AF_INET, SOCK_STREAM, 0);
//Define the server address
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(9002);
server_address.sin_addr.s_addr = INADDR_ANY;
//Bind the socket to the IP and port
bind(server_socket, (struct sockaddr *) &server_address,
sizeof(server_address));
//Listen for connections
listen(server_socket, 5);
//Accept the connection
int client_socket = accept(server_socket, NULL, NULL);
//Send message
send(client_socket, server_message, sizeof(server_message), 0);
//Close the socket
close(server_socket);
}
return 0;
}
Upvotes: 3
Views: 597
Reputation: 68
Change the code like this(omitted error checking):
int main() {
//Create a socket
int server_socket;
server_socket = socket(AF_INET, SOCK_STREAM, 0);
//Define the server address
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(9002);
server_address.sin_addr.s_addr = INADDR_ANY;
//Bind the socket to the IP and port
bind(server_socket, (struct sockaddr *) &server_address,
sizeof(server_address));
//Listen for connections
listen(server_socket, 5);
while(1) {
char server_message[256] = "You have reached the server!";
//Accept the connection
int client_socket = accept(server_socket, NULL, NULL);
/*check some condition to exit from loop*/
/*or send client to another thread for parallel programing*/
//Send message
send(client_socket, server_message, sizeof(server_message), 0);
//Close the client socket
close(client_socket);
}
close(server_socket);
return 0;
}
in this code server after get client must wait the client finished it's job and then try to accept new client, if you want parallel, accept client and data transfer in client, it's better to put client send and receive in another thread.
Upvotes: 0
Reputation: 310909
You're looping creating a server socket, accepting one connection, processing it, and then closing your server socket. The last action will throw away all pending connections. Your loop should start immediately after the listen()
call and terminate after closing the client socket, and before closing the server socket.
You are also ignoring all errors on socket(), bind(), listen(), accept(), send()
, and close()
. Don't do that.
Upvotes: 2