文章目录
- 目标
- 服务器与客户端通信流程
- TCP服务器代码
- TCP客户端代码
目标
实现客户端连接服务器,通过终端窗口发送信息给服务器端,服务器接收到信息后对信息数据进行回传,客户端读取回传信息并返回。
服务器与客户端通信流程
TCP服务器代码
服务器当前IP地址要知道
建立socket
绑定本地IP地址并设置端口号
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
int main()
{
//socket套接字
int lfd = socket(AF_INET, SOCK_STREAM, 0);
if(lfd == -1)
{
perror("socket");
exit(-1);
}
//绑定
struct sockaddr_in saddr;
saddr.sin_family = AF_INET;
inet_pton(AF_INET, "192.168.1.108", &saddr.sin_addr.s_addr);
//saddr.sin_addr.s_addr = INADDR_ANY;//做服务器时表示可以通过任意网卡都可以连接进来
saddr.sin_port = htons(9999);//转换成网络字节序
int bindret = bind(lfd, (struct sockaddr *)&saddr, sizeof(saddr));
if(bindret == -1)
{
perror("bind");
exit(-1);
}
//监听
int ret = listen(lfd, 8);
if(ret == -1)
{
perror("listen");
exit(-1);
}
//等待连接
struct sockaddr_in clientaddr;
int len = sizeof(clientaddr);
int cfd = accept(lfd, (struct sockaddr *)&clientaddr, &len);
if(cfd == -1)
{
perror("accept");
exit(-1);
}
char clientIP[len];
inet_ntop(AF_INET, &clientaddr.sin_addr, clientIP, len);
printf("client IP:%s Port:%d\n", clientIP, ntohs(clientaddr.sin_port));
while (1)
{
//接收数据
char rbuf[1024];
len = read(cfd, rbuf, sizeof(rbuf));
if(len == -1)
{
perror("read");
exit(-1);
}
else if(len == 0)
{
printf("Client close...\n");
}
else if(len > 0)
{
printf("resive data: %s\n", rbuf);
}
//发送数据
char sbuf[] = "i am server\n";
write(cfd, rbuf, sizeof(rbuf));
}
//关闭连接
close(cfd);
close(lfd);
return 0;
}
TCP客户端代码
知道服务器的IP地址和端口号
然后进行连接
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
int main()
{
//socket套接字
int lfd = socket(AF_INET, SOCK_STREAM, 0);
if(lfd == -1)
{
perror("socket");
exit(-1);
}
//连接
struct sockaddr_in saddr;
saddr.sin_family = AF_INET;
inet_pton(AF_INET, "192.168.1.108", &saddr.sin_addr.s_addr);
saddr.sin_port = htons(9999);//转换成网络字节序
int connect_cont = 3;
int ret;
jx_connect:
ret = connect(lfd, (struct sockaddr *)&saddr, sizeof(saddr));
if(ret == -1)
{
perror("connect");
sleep(2);
connect_cont--;
if(connect_cont) goto jx_connect;
exit(-1);
}
printf("client link success!\n");
//通信
char rbuf[1024];
while(1)
{
//发送数据
char sbuf[] = "i am client\n";
fgets(rbuf, 1024, stdin);
write(lfd, rbuf, sizeof(rbuf));
//接收数据
int len = read(lfd, rbuf, sizeof(rbuf));
if(len == -1)
{
perror("read");
exit(-1);
}
else if(len == 0)
{
printf("Client close...\n");
break;
}
else if(len > 0)
{
printf("resive data: %s\n", rbuf);
}
sleep(1);
}
//关闭连接
close(lfd);
return 0;
}