目标
实现客户端连接服务器,通过终端窗口发送信息给服务器端,服务器接收到信息后对信息数据进行回传,客户端读取回传信息并返回。
服务器与客户端通信流程
TCP服务器代码
服务器当前IP地址要知道
建立socket
绑定本地IP地址并设置端口号文章来源:https://www.toymoban.com/news/detail-628494.html
#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地址和端口号
然后进行连接文章来源地址https://www.toymoban.com/news/detail-628494.html
#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;
}
到了这里,关于Linux下TCP网络服务器与客户端通信程序入门的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!