0% found this document useful (0 votes)
12 views2 pages

Socket Server Test

This C program implements a simple TCP server that listens on port 8080. It accepts incoming connections and sends a 'Hello from server' message to the client every 2 seconds for a total of 1000 times. The server handles socket creation, binding, and listening for connections before sending messages and closing the sockets.

Uploaded by

lijiade
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views2 pages

Socket Server Test

This C program implements a simple TCP server that listens on port 8080. It accepts incoming connections and sends a 'Hello from server' message to the client every 2 seconds for a total of 1000 times. The server handles socket creation, binding, and listening for connections before sending messages and closing the sockets.

Uploaded by

lijiade
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define PORT 8080

int main() {
int server_fd, new_socket;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};
const char *hello = "Hello from server";

// Creating socket file descriptor


if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}

// Forcefully attaching socket to the port 8080


if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &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 specified port


if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}

// Listening for connections


if (listen(server_fd, 3) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}

// Accept incoming connections


if ((new_socket = accept(server_fd, (struct sockaddr *)&address,
(socklen_t*)&addrlen)) < 0) {
perror("accept");
exit(EXIT_FAILURE);
}

// Sending message to the client


for (int i = 0; i < 1000; i++)
{
send(new_socket, hello, strlen(hello), 0);
printf("Hello message sent to client\n");
sleep(2);
}

// Close the socket


close(new_socket);
close(server_fd);
return 0;
}

You might also like