Created
March 11, 2014 05:04
-
-
Save suxue/9479776 to your computer and use it in GitHub Desktop.
multi-process tcp echo server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifdef _win32_ | |
#include <winsock2.h> | |
#else | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <arpa/inet.h> | |
#include <netinet/in.h> | |
#include <strings.h> | |
#include <unistd.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <signal.h> | |
#include <errno.h> | |
#endif | |
#define SERV_PORT 7777 | |
#define LISTENQ 1024 | |
#define SA struct sockaddr | |
#define BUF_SIZE 1024 | |
static char buffer[BUF_SIZE]; | |
void | |
send_buf(int fd, size_t len) | |
{ | |
size_t count = 0, t; | |
while ((((t = write(fd, buffer, len - count)) >= 0) || errno == EINTR) | |
&& (count != len)) { | |
count += t > 0 ? t : 0; | |
} | |
} | |
void | |
str_echo(int fd) | |
{ | |
size_t t; | |
for ( ; ; ) { | |
t = read(fd, buffer, sizeof(buffer)); | |
if (t > 0) { | |
send_buf(fd, t); | |
} else if (t == 0) { // 0 => EOF | |
break; | |
} else if (t < 0) { | |
if (errno != EINTR) { | |
break; | |
} else | |
continue; | |
} | |
} | |
} | |
int | |
main(int argc, char *argv[]) | |
{ | |
int listenfd, connfd; | |
pid_t childpid; | |
socklen_t chilen; | |
struct sockaddr_in cliaddr, servaddr; | |
listenfd = socket(AF_INET, SOCK_STREAM, 0); | |
bzero(&servaddr, sizeof(servaddr)); | |
servaddr.sin_family = AF_INET; | |
servaddr.sin_addr.s_addr = htonl(INADDR_ANY); | |
servaddr.sin_port = htons(SERV_PORT); | |
bind(listenfd, (SA*) &servaddr, sizeof(servaddr)); | |
listen(listenfd, LISTENQ); | |
for (; ;) { | |
chilen = sizeof(cliaddr); | |
connfd = accept(listenfd, (SA*) &cliaddr, &chilen); | |
if ( (childpid = fork()) == 0) { | |
close(listenfd); | |
str_echo(connfd); | |
exit(0); | |
} | |
close(connfd); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment