TCP服务器demo
基于TCP服务器, fork多进程并发服务器
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/signal.h>
#include <sys/wait.h>
#define BUF_SIZE 256
#define HOST_PORT 65423
#define LISTEN_SIZE 4
void signal_hander(int sig)
{
waitpid(-1, NULL, WNOHANG);
}
int main(int argc, const char *argv[])
{
printf("HOST_PORT is %d\n", HOST_PORT);
if(signal(SIGCHLD, signal_hander) == SIG_ERR)
{
perror("Signal");
return -1;
}
char recvbuf[BUF_SIZE] = {0};
char sendbuf[BUF_SIZE] = {0};
int sendbuf_size = sizeof(sendbuf);
int recvbuf_size = sizeof(recvbuf);
struct sockaddr_in serveraddr, clientaddr;
int serveraddr_size = sizeof(serveraddr);
int clientaddr_size = sizeof(clientaddr);
memset(&serveraddr, 0, serveraddr_size);
memset(&clientaddr, 0, clientaddr_size);
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd == -1)
{
perror("Socket");
return -1;
}
socklen_t enble_reuseAddr = 1;
int ret = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &enble_reuseAddr, sizeof(enble_reuseAddr));
if(ret == -1)
{
perror("Setsockopt");
close(sockfd);
return -1;
}
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(HOST_PORT);
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
int rebind = bind(sockfd, (struct sockaddr*)&serveraddr, serveraddr_size);
if(rebind == -1)
{
perror("Bind");
close(sockfd);
return -1;
}
int relisten = listen(sockfd, LISTEN_SIZE);
if(relisten == -1)
{
perror("Listen");
close(sockfd);
return -1;
}
while(1)
{
printf("Waiting for client connection ....\n");
int connectfd = accept(sockfd, (struct sockaddr*)&clientaddr, &clientaddr_size);
if(connectfd == -1)
{
perror("Accept");
close(sockfd);
return -1;
}
printf("\nClient connection succeeded ....\n");
printf("Client ip is : %s\n", inet_ntoa(clientaddr.sin_addr));
printf("Client port is : %d\n", ntohs(clientaddr.sin_port));
pid_t pid = fork();
switch(pid)
{
case -1:
{
perror("Fock");
close(sockfd);
close(connectfd);
exit(-1);
break;
}
case 0:
{
close(sockfd);
while(1)
{
memset(recvbuf, 0, recvbuf_size);
memset(sendbuf, 0, sendbuf_size);
int recv_len = recv(connectfd, recvbuf, recvbuf_size, 0);
if(recv_len == -1)
{
perror("Recv");
close(connectfd);
exit(-1);
}else if(recv_len == 0)
{
printf("Client disconnect IP: %s Port: %d\n", inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port));
close(connectfd);
exit(0);
}
puts(recvbuf);
strcpy(sendbuf, recvbuf);
send(connectfd, sendbuf, strlen(sendbuf), 0);
}
close(connectfd);
break;
}
default:
{
continue;
}
}
}
close(sockfd);
return 0;
}
|