必需感慨一下,网络程序的细节真的是太多了,任何一个步骤都有可能出现问题!而且还要处理所遇到的问题!!!
服务器:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define SERV_PORT 9978
#define LISTENQ 5
#define MAXLINE 4096
typedef struct sockaddr SA;
int
main(int argc, char *agrv[])
{
void str_echo(int sockfd) ;
int listenfd, connfd;
pid_t childpid;
socklen_t clilen;
struct sockaddr_in cliaddr, servaddr;
listenfd = socket(AF_INET, SOCK_STREAM, 0); // maybe have errror
memset(&servaddr, 0, 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)); // maybe have error
listen(listenfd, LISTENQ); // maybe have error
for (;;) {
clilen = sizeof(cliaddr);
connfd = accept(listenfd, (SA *)&cliaddr, &clilen); // maybe have error
if ((childpid = fork()) == 0) { // maybe have error
close(listenfd);
str_echo(connfd); // deal connfd
// close(connfd); // unnecessary statement
exit(0);
}
close(connfd); // maybe have error
}
return 0;
}
void
str_echo(int sockfd)
{
ssize_t n;
char buf[MAXLINE];
do {
while ( (n=read(sockfd, buf, MAXLINE)) >0)
write(sockfd, buf, n);
} while (n<0 && errno==EINTR);
if (n<0) {
perror("str_echo:read error");
exit(1);
}
}
客户端
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define SERV_PORT 9978
#define LISTENQ 5
#define MAXLINE 4096
typedef struct sockaddr SA;
int
main(int argc, char *argv[])
{
void str_cli(FILE *fp, int sockfd);
int sockfd;
struct sockaddr_in servaddr;
if (argc != 2) {
perror("usage: tcpcli <IPaddress>");
exit(-1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&sockfd, 0, sizeof(sockfd));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(SERV_PORT);
inet_pton(AF_INET, argv[1], &servaddr.sin_addr);
connect(sockfd, (SA *)&servaddr, sizeof(servaddr));
str_cli(stdin, sockfd);
exit(0);
return 0;
}
void
str_cli(FILE *fp, int sockfd)
{
char sendline[MAXLINE], recvline[MAXLINE];
while (fgets(sendline, MAXLINE, fp) != NULL) {
write(sockfd, sendline, strlen(sendline));
if (read(sockfd, recvline, MAXLINE) == 0) {
perror("str_cli: server teminated prematurely");
}
fputs(recvline, stdout);
}
}