73 lines
1.6 KiB
C
73 lines
1.6 KiB
C
#include <netdb.h>
|
|
#include <netinet/in.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <sys/socket.h>
|
|
#include <sys/types.h>
|
|
#include <unistd.h>
|
|
|
|
#define MAX 80
|
|
#define PORT 8080
|
|
|
|
void func(int connfd) {
|
|
char buff[MAX];
|
|
|
|
for (;;) {
|
|
bzero(buff, MAX);
|
|
|
|
ssize_t recv_n = recv(connfd, buff, sizeof(buff), 0);
|
|
if (recv_n >= MAX) {
|
|
/* Likely more data, realloc */
|
|
}
|
|
|
|
buff[recv_n - 1] = '\0';
|
|
printf("From client: %s\n", buff);
|
|
bzero(buff, MAX);
|
|
|
|
char *msg = "Hello!\n";
|
|
send(connfd, msg, strlen(msg), 0);
|
|
|
|
if (strncmp("exit", buff, 4) == 0) {
|
|
printf("Server Exit...\n");
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
int main() {
|
|
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
|
|
if (sockfd == -1) {
|
|
printf("socket creation failed...\n");
|
|
exit(0);
|
|
}
|
|
|
|
struct sockaddr_in servaddr;
|
|
bzero(&servaddr, sizeof(servaddr));
|
|
|
|
servaddr.sin_family = AF_INET;
|
|
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
|
|
servaddr.sin_port = htons(PORT);
|
|
|
|
if ((bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr))) != 0) {
|
|
printf("socket bind failed...\n");
|
|
exit(0);
|
|
}
|
|
|
|
if ((listen(sockfd, 5)) != 0) {
|
|
printf("Listen failed...\n");
|
|
exit(0);
|
|
}
|
|
|
|
struct sockaddr_in cli;
|
|
socklen_t len = sizeof(cli);
|
|
|
|
int connfd = accept(sockfd, (struct sockaddr *)&cli, &len);
|
|
if (connfd < 0) {
|
|
printf("server accept failed...\n");
|
|
exit(0);
|
|
}
|
|
|
|
func(connfd);
|
|
close(sockfd);
|
|
}
|