服务器:
/*
*tcp_server.c
*/ #include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <signal.h> #define SER_PORT 8000
#define MAX_LINE 1024 void str_echo(int sockfd);
void sig_chld(int signo); int main(int argc, char **argv)
{
int listenfd, connfd;
struct sockaddr_in servaddr, cliaddr;
socklen_t cliaddr_len;
char buff[MAX_LINE];
pid_t childpid; listenfd = socket(AF_INET, SOCK_STREAM, ); bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SER_PORT); bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr)); listen(listenfd, );
signal(SIGCHLD, sig_chld); while()
{
cliaddr_len = sizeof(cliaddr);
connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &cliaddr_len);
printf("receive from %s at port %d\n", inet_ntop(AF_INET, &cliaddr.sin_addr, buff, sizeof(buff)), ntohs(cliaddr.sin_port)); if ((childpid = fork()) == ) /* child process */
{
printf("child process pid = %d\n", (int)childpid);
close(listenfd);
str_echo(connfd);
printf("child process terminated\n");
exit();
} close(connfd);
} return ;
} void str_echo(int sockfd)
{
ssize_t n;
char buf[MAX_LINE] = {}; AGAIN:
while ((n = read(sockfd, buf, MAX_LINE)) > )
{
printf("%s\n", buf);
write(sockfd, buf, n);
bzero(buf, sizeof(buf));
} if (n < && errno == EINTR)
{
goto AGAIN;
}
else if (n < )
{
printf("read error\n");
}
else
{
printf("str_echo: read EOF\n");
} } void sig_chld(int signo)
{
pid_t pid;
int stat; pid = wait(&stat);
printf("child %d terminated\n", pid); return;
}
客户端:
/*
*tcp_client.c
*/ #include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <string.h> #define SER_PORT 8000
#define MAX_LINE 1024 void str_cli(FILE *fp, int sockfd); int main(int argc, char **argv)
{
int sockfd;
struct sockaddr_in servaddr; sockfd = socket(AF_INET, SOCK_STREAM, ); bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
inet_pton(AF_INET, "127.0.0.1", &servaddr.sin_addr);
servaddr.sin_port = htons(SER_PORT); if(connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < )
{
printf("connect error:%s\n", strerror(errno));
return ;
} str_cli(stdin, sockfd); return ;
} void str_cli(FILE *fp, int sockfd)
{
char sendline[MAX_LINE] = {};
char recvline[MAX_LINE] = {}; while (fgets(sendline, MAX_LINE, fp) != NULL)
{
write(sockfd, sendline, strlen(sendline)); if (read(sockfd, recvline, MAX_LINE) == )
{
printf("server terminated\n");
break;
}
fputs(recvline, stdout); bzero(sendline, sizeof(sendline));
bzero(recvline, sizeof(recvline));
}
}
参考:
《UNIX网络编程 - 卷1:套接字联网API》