/* * server.c - demo program that connects listens for connections on PORT * receives message from client, responds with message back to client * this program has only minor edits to the original at https://www.geeksforgeeks.org/socket-programming-cc/ * works with client.c * first start the server running, then in a separate terminal start the client running * * usage: ./server * compile: gcc -o server server.c * * * author: Geeks for Geeks Tim Pierson, Fall 2022, minor edits * CS 50, Fall 2022 */ #include #include #include #include #include #include const int PORT = 8080; /** Set up server socket to listen for client connections * When connection made, read message from client * respond to client with message from this server * * int num_players - max number of connections to accept */ void get_players(int num_players) { int server_fd, new_socket, valread; struct sockaddr_in address; int opt = 1; int addrlen = sizeof(address); char buffer[1024] = { 0 }; char* hello = "Hello from server"; printf("Setting up socket\n"); // Creating socket file descriptor if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) { perror("socket failed"); exit(EXIT_FAILURE); } // Attaching socket to the PORT if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) { perror("setsockopt"); exit(EXIT_FAILURE); } address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(PORT); // Binding socket to the PORT if (bind(server_fd, (struct sockaddr*)&address, sizeof(address)) < 0) { perror("bind failed"); exit(EXIT_FAILURE); } if (listen(server_fd, num_players) < 0) { perror("listen"); exit(EXIT_FAILURE); } printf("Waiting for connection... "); fflush(stdout); //ensure line above prints before waiting for connection if ((new_socket = accept(server_fd, (struct sockaddr*)&address, (socklen_t*)&addrlen)) < 0) { printf("\n"); perror("accept"); exit(EXIT_FAILURE); } printf("Someone connected\n"); valread = read(new_socket, buffer, 1024); if (valread < 0) { perror("reading message"); exit(EXIT_FAILURE); } printf("Message from client: %s\n", buffer); printf("Sending %s to client\n",hello); send(new_socket, hello, strlen(hello), 0); printf("Message sent\n"); // closing the connected socket close(new_socket); // closing the listening socket shutdown(server_fd, SHUT_RDWR); } int main(int argc, char* argv[]) { int num_players = 1; get_players(num_players); return 0; }