详见注释:
server_process.c:
#include <stdio.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main(){
//创建socket
int lfd = socket(PF_INET, SOCK_STREAM,0);
if(lfd == -1){
perror("socket");
exit(-1);
}
//绑定
struct sockaddr_in saddr;
saddr.sin_addr.s_addr = INADDR_ANY;//其实就是0
saddr.sin_family = AF_INET;
saddr.sin_port = htons(9999);
int ret = bind(lfd, (struct sockaddr *)&saddr,sizeof(saddr));
if(ret == -1){
perror("bind");
exit(0);
}
//监听
ret = listen(lfd, 128);
if(ret == -1){
perror("listen");
exit(-1);
}
//不断循环等待客户端连接
while(1){
//接收连接
struct sockaddr_in cliaddr;
int len = sizeof(cliaddr);
int cfd = accept(lfd,(struct sockaddr*)&cliaddr,&len);
if(cfd == -1){
perror("accept");
exit(-1);
}
//每一个连接进来,就创建一个子进程跟客户端通信
pid_t pid = fork();
if(pid == 0){
//子进程
//获取客户端的信息
char cliIP[16];
inet_ntop(AF_INET,&cliaddr.sin_addr.s_addr,cliIP,sizeof(cliIP));
unsigned short cliPort = ntohs(cliaddr.sin_port);
printf("client ip is : %s, port is %d\n",cliIP,cliPort);
//接收客户端发来的数据
char recvBuf[1024] = {0};
while(1){
int len = read(cfd, &recvBuf, sizeof(recvBuf));
if(len == -1){
perror("read");
exit(-1);
}else if(len > 0){
printf("recv client data : %s\n",recvBuf);
}else
{
printf("client closed...");
}
write(cfd, recvBuf,strlen(recvBuf));
}
close(cfd);
exit(0);//退出当前子进程
}
}
close(lfd);
return 0;
}
client.c:
//TCP 通信的客户端
#include <stdio.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main(){
// 1.创建套接字
int fd = socket(AF_INET, SOCK_STREAM,0);
if(fd == -1){
perror("socket");
exit(-1);
}
// 2.连接服务器端
struct sockaddr_in serveraddr;
serveraddr.sin_family = AF_INET;
inet_pton(AF_INET, "127.0.0.1", &serveraddr.sin_addr.s_addr);
serveraddr.sin_port = htons(9999);
int ret = connect(fd, (struct sockaddr *)&serveraddr, sizeof(serveraddr));
if(ret == -1){
perror("connect");
exit(-1);
}
// 3.通信
char recvBuf[1024];
int i = 0;
while (1)
{
sprintf(recvBuf, "data : %d\n",i++);
//给服务器发送数据
write(fd, recvBuf,sizeof(recvBuf));
int len = read(fd,recvBuf,sizeof(recvBuf));
if(len == -1){
perror("read");
exit(-1);
}else if(len > 0){
printf("recv server data : %s\n",recvBuf);
}else if(len == 0){
//表示服务器断开连接
printf("server closed...");
break;
}
sleep(1);
}
//关闭连接
close(fd);
return 0;
}