服务端的简单模型:
int lfd=socket(AF_INET,SOCK_STREAM,0) ;
int ret =bind(lfd,(struct sockaddr*)&addr,sizeof addr) ;
listen(lfd,SOMAXCONN) ;
int nfd=accept(lfd,NULL,NULL) ;
while(1){
read() ;
parse() ;
write() ;
}
// 客户端简单代码 tcp_cli.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/types.h>
int main(){
int lfd = socket(AF_INET,SOCK_STREAM,0) ;
struct sockaddr_in addr ;
addr.sin_family = AF_INET ;
addr.sin_port = htons(10002) ;
inet_aton("192.168.73.156",&addr.sin_addr) ;
int ret = connect(lfd,(struct sockaddr*)&addr,sizeof addr) ;
if(ret == -1){
perror("connect") ;
exit(0) ;
}
char buf[1024] = {} ;
while(fgets(buf,1023,stdin) != NULL){
write(lfd,buf,strlen(buf)) ;
memset(buf,0x00,sizeof buf) ;
ret = read(lfd,buf,1023) ;
printf("client => %s\n",buf) ;
if(ret == 0){
break ;
}
}
return 0 ;
}
// tcp_svr_more.c
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <signal.h>
#include <sys/wait.h>
void parse(char* buf){
for(int i = 0 ; buf[i] ; ++i)
if(buf[i]>='a' && buf[i]<='z')
buf[i] -= 'a' - 'A' ;
}
void handler(int s){
printf("kill %d\n",s) ;
// wait(NULL) ;
while(waitpid(-1,0,WNOHANG) != -1) ;
}
int main(){
struct sigaction act ;
act.sa_handler = handler ;
act.sa_flags = 0 ;
sigemptyset(&act.sa_mask) ;
sigaction(SIGCHLD,&act,NULL) ;
printf("create socket sucess\n") ;
struct sockaddr_in addr ;
addr.sin_family = AF_INET ;
addr.sin_port = htons(10002) ;
inet_aton("192.168.73.156",&addr.sin_addr) ;
int ret = bind(lfd,(struct sockaddr*)&addr,sizeof addr) ;
if(ret == -1){
perror("bind") ;
exit(1) ;
}
printf("bind sucess\n") ;
ret = listen(lfd,SOMAXCONN) ;
if(ret==-1){
perror("listen") ;
exit(1) ;
}
printf("listen sucess\n") ;
for(;;){
// accept : 第二、三个参数为客户端的详细内容
int nfd = accept(lfd,NULL,NULL) ;
// when parent process with ctrl+C signal
if(errno == EINTR && nfd == -1){
perror("accept") ;
continue ;
}
printf("accept sucess\n") ;
pid_t pid = fork() ;
// child process deal with this task
if( pid == 0){
while(1){
char buf[1024] = {} ;
ret = read(nfd,buf,1023) ;
printf("buf = %s\n",buf) ;
if(ret == 0){
break ;
}
parse(buf) ;
write(nfd,buf,ret) ;
}
close(nfd) ;
close(lfd) ;
exit(0) ;
}
close(nfd) ;
}
close(lfd) ;
return 0 ;
}