开发环境
1、讯为RK3568开发板,下载了Ubuntu系统。
2、笔记本Windows下的VScode连接开发板。
3、网线连接开发板J13网口。
VSCode远程连接开发板:
https://blog.csdn.net/u012507643/article/details/152666866?spm=1011.2124.3001.6209
TCP服务器收发的流程:
创建socket->bind本地ip->listen->accept->sendto/recvfrom
一、用到的函数
1、函数参考前面写的一片博客,这里不复制过来了
2、listen
int listen (int __fd, int __n)
__fd:本地的IP端口套接字描述符。【RK3568开发板的】
__n:可以监听的客户端队列数量
3、accept
int accept (int __fd, __SOCKADDR_ARG __addr,
socklen_t *__restrict __addr_len);
__fd:本地的IP端口套接字描述符。【RK3568开发板的】
__addr:新建用于绑定连接的客户端信息
return:-1失败。成功返回新客户端套接字描述符
二、直接看实际代码
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <linux/tcp.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
int fd, client_fd;
struct sockaddr_in s;
struct sockaddr_in c;
int len = sizeof(c), rlen = 0;
char rx_buf[1024] = {0};
fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0)
{
printf("create socekt failed\n");
return 1;
}
//绑定本机IP信息
s.sin_family = AF_INET;
s.sin_port = htons(8089);
inet_pton(AF_INET, "192.168.31.96", &s.sin_addr);
bind(fd, (const struct sockaddr *)&s, sizeof(s));
//监听客户端
printf("start listen\n");
if (listen(fd, 10) < 0) {
printf("listen failed\n");
return 1;
}
printf("server ip:192.168.31.96,port:8089\n");
/* 返回连接上来的套接字 */
client_fd = accept(fd, (struct sockaddr *)&c, &len);
if (client_fd < 0)
{
printf("sccept failed\n");
return 1;
}
printf("new client connected\n");
while(1)
{
rlen = recvfrom(client_fd, rx_buf, sizeof(rx_buf), 0, (struct sockaddr *)&c, &len);
if (rlen > 0)
{
printf("recv data:%s,len=%d\n", rx_buf, rlen);
send(client_fd, rx_buf, rlen, MSG_DONTWAIT);
memset(rx_buf, 0, sizeof(rx_buf));
}
}
close(fd);
close(client_fd);
return 0;
}
三、测试
1、连接

2、收发数据

四、总结
1、这里其实是还有一个问题:客户端断开重连时候的套接字应该是不一样了。所以,客户端断开重连后就发送接收不到了,下一篇更新。
2、这里recv接收数据flag不能设置成MSG_DNOTWAIT,这里设置0阻塞。

1435

被折叠的 条评论
为什么被折叠?



