TCP网络通讯如何解决分包粘包问题(有模拟代码)
一、TCP粘包情况:


- /**
- * read size of len from sock into buf.
- */
- bool readPack(int sock, char* buf, size_t len) {
- if (NULL == buf || len < 1) {
- return false;
- }
- memset(buf, 0, len); // only reset buffer len.
- ssize_t read_len = 0, readsum = 0;
- do {
- read_len = read(sock, buf + readsum, len - readsum);
- if (-1 == read_len) { // ignore error case
- return false;
- }
- printf("receive data: %s\n", buf + readsum);
- readsum += read_len;
- } while (readsum < len && 0 != read_len);
- return true;
- }
二、测试用例介绍
三、源码实现
- #include <cstdio>
- #include <cstdlib>
- #include <cstring>
- #include <errno.h>
- #include <sys/socket.h>
- #include <sys/types.h>
- #include <arpa/inet.h>
- #include <unistd.h>
- void newclient(int sock);
- bool readPack(int sock, char* buf, size_t len);
- void safe_close(int &sock);
- int main(int argc, char *argv[]) {
- int sockfd = -1, newsockfd = -1;
- socklen_t c = 0;
- struct sockaddr_in serv_addr, cli_addr;
- // Create socket
- sockfd = socket(AF_INET, SOCK_STREAM, 0);
- if (-1 == sockfd) {
- printf("new socket failed. errno: %d, error: %s\n", errno, strerror(errno));
- exit(-1);
- }
- // Prepare the sockaddr_in structure
- serv_addr.sin_family = AF_INET;
- serv_addr.sin_addr.s_addr = INADDR_ANY;
- serv_addr.sin_port = htons(7890);
- // bind
- if (bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
- printf("bind failed. errno: %d, error: %s\n", errno, strerror(errno));
- exit(-1);
- }
- // listen
- listen(sockfd, 5);
- printf("listening...\n");
- // accept new connection.
- c = sizeof(struct sockaddr_in);
- int i = 0;
- while (i++ < 3) {
- printf("waiting for new socket accept.\n");
- newsockfd = accept(sockfd, (struct sockaddr*)&cli_addr, (socklen_t*)&c);
- if (newsockfd < 0) {
- printf("accept connect failed. errno: %d, error: %s\n", errno, strerror(errno));
- safe_close(sockfd);
- exit(-1);
- }
- pid_t pid = fork();
- if (0 == pid) {
- newclient(newsockfd);
- safe_close(sockfd);
- break;
- } else if (pid > 0) {
- safe_close(newsockfd);
- }
- }
- safe_close(sockfd);
- return 0;
- }
- void newclient(int sock) {
- printf("newclient sock fd: %d\n", sock);
- int datasize = 0;
- const int HEAD_SIZE = 9;
- char buf[512] = {0};
- while (true) {
- memset(buf, 0, sizeof(buf));
- if (! readPack(sock, buf, HEAD_SIZE)) {
- printf("read head buffer failed.\n");
- safe_close(sock);
- return;
- }
- datasize = atoi(buf);
- printf("data size: %s, value:%d\n", buf, datasize);
- memset(buf, 0, sizeof(buf));
- if (! readPack(sock, buf, datasize)) {
- printf("read data buffer failed\n");
- safe_close(sock);
- return;
- }
- printf("data size: %d, text: %s\n", datasize, buf);
- if (0 == strcmp(buf, "exit")) {
- break;
- }
- }
- memset(buf, 0, sizeof(buf));
- snprintf(buf, sizeof(buf), "from server read complete.");
- write(sock, buf, strlen(buf) + 1);
- printf("newclient sockfd: %d, finish.\n", sock);
- safe_close(sock);
- }
- void safe_close(int &sock) {
- if (sock > 0) {
- close(sock);
- sock = -1;
- }
- }
- /**
- * read size of len from sock into buf.
- */
- bool readPack(int sock, char* buf, size_t len) {
- if (NULL == buf || len < 1) {
- return false;
- }
- memset(buf, 0, len); // only reset buffer len.
- ssize_t read_len = 0, readsum = 0;
- do {
- read_len = read(sock, buf + readsum, len - readsum);
- if (-1 == read_len) { // ignore error case
- return false;
- }
- printf("receive data: %s\n", buf + readsum);
- readsum += read_len;
- } while (readsum < len && 0 != read_len);
- return true;
- }
client.cpp
- #include <cstdio>
- #include <cstdlib>
- #include <cstring>
- #include <time.h>
- #include <errno.h>
- #include <sys/socket.h>
- #include <arpa/inet.h>
- #include <unistd.h>
- void safe_close(int &sock);
- void emulate_subpackage(int sock);
- void emulate_adheringpackage(int sock);
- int main(int argc, char *argv[]) {
- char buf[128] = {0};
- int sockfd = -1;
- struct sockaddr_in serv_addr;
- // Create sock
- sockfd = socket(AF_INET, SOCK_STREAM, 0);
- if (-1 == sockfd) {
- printf("new socket failed. errno: %d, error: %s\n", errno, strerror(errno));
- exit(-1);
- }
- serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
- serv_addr.sin_family = AF_INET;
- serv_addr.sin_port = htons(7890);
- // Connect to remote server
- if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
- printf("connection failed. errno: %d, error: %s\n", errno, strerror(errno));
- exit(-1);
- }
- emulate_subpackage(sockfd);
- emulate_adheringpackage(sockfd);
- const int HEAD_SIZE = 9;
- const char temp[] = "exit";
- memset(buf, 0, sizeof(buf));
- snprintf(buf, sizeof(buf), "%0.*zu", HEAD_SIZE - 1, sizeof(temp));
- write(sockfd, buf, HEAD_SIZE);
- write(sockfd, temp, sizeof(temp));
- printf("send complete.\n");
- memset(buf, 0, sizeof(buf));
- read(sockfd, buf, sizeof(buf));
- printf("receive data: %s\n", buf);
- printf("client finish.\n");
- safe_close(sockfd);
- return 0;
- }
- void safe_close(int &sock) {
- if (sock > 0) {
- close(sock);
- sock = -1;
- }
- }
- /**
- * emulate socket data write multi part.
- */
- void emulate_subpackage(int sock) {
- printf("emulate_subpackage...\n");
- char text[] = "This is a test case for client send subpackage data. data is not send complete at once.";
- const size_t TEXTSIZE = sizeof(text);
- ssize_t len = 0;
- size_t sendsize = 0, sendsum = 0;
- const int HEAD_SIZE = 9;
- char buf[64] = {0};
- snprintf(buf, HEAD_SIZE, "%08zu", TEXTSIZE);
- write(sock, buf, HEAD_SIZE);
- printf("send data size: %s\n", buf);
- do {
- sendsize = 6;
- if (sendsum + sendsize > TEXTSIZE) {
- sendsize = TEXTSIZE - sendsum;
- }
- len = write(sock, text + sendsum, sendsize);
- if (-1 == len) {
- printf("send data failed. errno: %d, error: %s\n", errno, strerror(errno));
- return;
- }
- memset(buf, 0, sizeof(buf));
- snprintf(buf, len + 1, text + sendsum);
- printf("send data: %s\n", buf);
- sendsum += len;
- sleep(1);
- } while (sendsum < TEXTSIZE && 0 != len);
- }
- /**
- * emualte socket data write adhering.
- */
- void emulate_adheringpackage(int sock) {
- printf("emulate_adheringpackage...\n");
- const int HEAD_SIZE = 9;
- char buf[1024] = {0};
- char text[128] = {0};
- char *pstart = buf;
- // append text
- memset(text, 0, sizeof(text));
- snprintf(text, sizeof(text), "Hello ");
- snprintf(pstart, HEAD_SIZE, "%08zu", strlen(text) + 1);
- pstart += HEAD_SIZE;
- snprintf(pstart, strlen(text) + 1, "%s", text);
- pstart += strlen(text) + 1;
- // append text
- memset(text, 0, sizeof(text));
- snprintf(text, sizeof(text), "I'm lucky.");
- snprintf(pstart, HEAD_SIZE, "%08zu", strlen(text) + 1);
- pstart += HEAD_SIZE;
- snprintf(pstart, strlen(text) + 1, "%s", text);
- pstart += strlen(text) + 1;
- // append text
- memset(text, 0, sizeof(text));
- snprintf(text, sizeof(text), "Nice too me you");
- snprintf(pstart, HEAD_SIZE, "%08zu", strlen(text) + 1);
- pstart += HEAD_SIZE;
- snprintf(pstart, strlen(text) + 1, "%s", text);
- pstart += strlen(text) + 1;
- write(sock, buf, pstart - buf);
- }
Makefile
- CC=g++
- CFLAGS=-I
- all: server.o client.o
- server.o: server.cpp
- $(CC) -o server.o server.cpp
- client.o: client.cpp
- $(CC) -o client.o client.cpp
- clean:
- rm *.o
四、测试结果
TCP网络通讯如何解决分包粘包问题(有模拟代码)的更多相关文章
- C#下利用封包、拆包原理解决Socket粘包、半包问题(新手篇)
介于网络上充斥着大量的含糊其辞的Socket初级教程,扰乱着新手的学习方向,我来扼要的教一下新手应该怎么合理的处理Socket这个玩意儿. 一般来说,教你C#下Socket编程的老师,很少会教你如何解 ...
- 解决Socket粘包问题——C#代码
解决Socket粘包问题——C#代码 前天晚上,曾经的一个同事问我socket发送消息如果太频繁接收方就会有消息重叠,因为当时在外面,没有多加思考 第一反应还以为是多线程导致的数据不同步导致的,让他加 ...
- Python之路(第三十一篇) 网络编程:简单的tcp套接字通信、粘包现象
一.简单的tcp套接字通信 套接字通信的一般流程 服务端 server = socket() #创建服务器套接字 server.bind() #把地址绑定到套接字,网络地址加端口 server.lis ...
- Python网络编程(2)-粘包现象及socketserver模块实现TCP并发
1. 基于Tcp的远程调用命令实现 很多人应该都使用过Xshell工具,这是一个远程连接工具,通过上面的知识,就可以模拟出Xshell远程连接服务器并调用命令的功能. Tcp服务端代码如下: impo ...
- 使用Newlife网络库管道模式解决数据粘包(二)
上一篇我们讲了 如何创建一个基本的Newlife网络服务端 这边我们来讲一下如何解决粘包的问题 在上一篇总我们注册了Newlife的管道处理器 ,我们来看看他是如何实现粘包处理的 svr.Add< ...
- 网络编程基础【day09】:解决socket粘包之大数据(七)
本节内容 概述 linux下运行效果 sleep解决粘包 服务端插入交互解决粘包问题 一.概述 刚刚我们在window的操作系统上,很完美的解决了,大数据量的数据传输出现的问题,但是在Linux环境下 ...
- TCP连接,传输数据时的粘包问题讨论
第一个需要讨论的大概就是粘包问题了.因为这个是TCP的个性问题,UDP通信时不存在这个问题的.首先看一下什么叫粘包: 客户端采取与服务器的长连接方式建立通信(Open-Write/Read-Write ...
- TCP Socket 套接字 和 粘包问题
一.Scoket 套接字 Scoket是应用层(应用程序)与TCP/IP协议通信的中间软件抽象层,它是一组接口.也可以理解为总共就三层:应用层,scoket抽象层,复杂的TCP/IP协议 基于TCP协 ...
- python------Socket网络编程(二)粘包问题
一.socket网络编程 粘包:服务端两次发送指令在一起,它会把两次发送内容合在一起发送,称为粘包,从而出现错误. 解决方法:(比较low的方法) 有些需要实时更新的,用sleep有延迟,不能这样解决 ...
随机推荐
- 项目中使用Prism框架
Prism框架在项目中使用 回顾 上一篇,我们介绍了关于控件模板的用法,本节我们将继续说明WPF更加实用的内容,在大型的项目中如何使用Prism框架,并给予Prism框架来构建基础的应用框架,并且 ...
- mysql分区功能(三个文件储存一张表)(分区作用)(分区方式)
mysql分区功能(三个文件储存一张表)(分区作用)(分区方式) 一.总结 1.mysql数据表的存储方式(三个文件储存一张表): 一张表主要对应着三个文件,一个是frm存放表结构的,一个是myd存放 ...
- HTML5 canvas 指针时钟
<!doctype html> <html> <head></head> <body> <canvas id="> 您 ...
- oracle listener.ora的host不能使localhost,而应该是该机器名,否则不能用ip地址进行连接
# listener.ora Network Configuration File: /u01/app/oracle/product/11.2.0/dbhome_1/network/admin/lis ...
- [Angular] Enable router tracing
To enable router tracing is really simple: RouterModule.forRoot(ROUTES, { enableTracing: true }) Whe ...
- [React Router v4] Style a Link that is Active with NavLink
We often need to be able to apply style to navigation links based on the current route. In React Rou ...
- html5-1 网页结构描述
html5-1 网页结构描述 一.总结 一句话总结:注意head中的title,keywords,description,这对seo优化很有帮助 1.如何给某元素动态使用类似onclick方法? 点o ...
- WPF实现射线效果动画
原文:WPF实现射线效果动画 最近的一个项目中有个需求是:从一个点向其它多个点发出射线,要求这些射线同时发出,同时到达. 我就想到了用WPF的动画来实现.WPF中有Line类用于绘制直线,但这个类中好 ...
- echarts改变颜色属性的demo
一:柱状图改变颜色 图片.png 代码: <!DOCTYPE html> <html> <head> <meta charset="UTF-8&qu ...
- [转]mnesia数据库学习笔记
mnesia数据库学习笔记一 mnesia数据库学习笔记二 mnesia数据库学习笔记三 mnesia数据库学习笔记四