使用TCP/IP协议实现客户端和服务器端进行通信:
1.服务器端(test1.c):
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
// 创建服务器端
int main()
{
//1.创建套接字
int serfd=socket(AF_INET,SOCK_STREAM,0);
if(serfd==-1)
{
printf("create socket failed\n");
return -1;
}
//2.绑定套接字和服务器地址
struct sockaddr_in addr;
addr.sin_family=AF_INET;
addr.sin_port=htons(8000);
addr.sin_addr.s_addr=inet_addr("127.0.0.1");
int ret=bind(serfd,(struct sockaddr*)&addr,sizeof(addr));
if(ret==-1)
{
printf("bind failed\n");
return -2;
}
//3.监听模式
ret=listen(serfd,10);
if(ret==-1)
{
printf("listen failed\n");
return -3;
}
//4. 等待客户端连接的到来
printf("waitting connect ......\n");
int clifd= accept(serfd,NULL,NULL);
if(clifd==-1)
{
printf("create client socket file failed\n");
return -4;
}
// 5. 读客户端发来的数据
char buff[100]={0};
read(clifd,buff,100);
printf("read content=%s\n",buff);
//6.关闭连接
close(clifd);//
close(serfd);
return 0;
}
2.客户端(test2.c):
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <stdio.h>
// 创建客户端
int main()
{
//1.create socket
int clifd=socket(AF_INET,SOCK_STREAM,0);
//2.客户端建立socket连线
struct sockaddr_in addr;
addr.sin_family=AF_INET;
addr.sin_port=htons(8000);
addr.sin_addr.s_addr=inet_addr("127.0.0.1");
int ret=connect(clifd,(struct sockaddr *)&addr,sizeof(addr));
if(ret==-1)
{
printf("connect failed\n");
return -1;
}
//3. 向客户端发送写的数据
write(clifd,"hello",6);
// 4.关闭客户端
close(clifd);
return 0;
}
运行结果: