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有延迟,不能这样解决 ...
随机推荐
- [转] Python 爬虫的工具列表 附Github代码下载链接
转自http://www.36dsj.com/archives/36417 这个列表包含与网页抓取和数据处理的Python库 网络 通用 urllib -网络库(stdlib). requests - ...
- ios开发之多线程---GCD
一:基本概念 1:进程:正在运行的程序为进程. 2:线程:每个进程要想执行任务必须得有线程,进程中任务的执行都是在线程中. 3:线程的串行:一条线程里任务的执行都是串行的,假如有一个进程开辟了一条线程 ...
- mui列表跳转到详情页优化方案
原理 因为列表页到详情页是多对一的形式,即列表页的多条数据列表对应的是一个详情页,只是数据不同而:因此,可以在加载列表页时预加载详情页,即创建一个详情页的webview,但是不显示出来,点击列表的时候 ...
- [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 ...
- [Angular] USING ZONES IN ANGULAR FOR BETTER PERFORMANCE
Link to the artical. Zone detects any async opreations. Once an async oprations happens in Angular, ...
- asp.net core2.0 部署centos7/linux系统 --守护进程supervisor(二)
原文:asp.net core2.0 部署centos7/linux系统 --守护进程supervisor(二) 续上一篇文章:asp.net core2.0 部署centos7/linux系统 -- ...
- SpringMVC中支持多视图解析
版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/suo082407128/article/details/70173301 在SpringMVC模式当 ...
- System and method for dynamically adjusting to CPU performance changes
FIELD OF THE INVENTION The present invention is related to computing systems, and more particularly ...
- solrj 7.x Expected mime type application/octet-stream but got text/html.
出现这种情况是因为baseurl填写错误,最开始的时候我写的是用tomcat启动后浏览器中访问solr的地址 结果就出现了如题的异常,当然提示的是404,还有可能提示405,Method not al ...
- CentOS下Apache的停止和卸载
昨晚搞到一台全球性价比最高的服务器,折腾一晚上,好不容易把node服务开启了,结果访问不了我的网站!!! 访问我的网站,显示的是一个Apache欢迎页面.我想,是不是像之前那样,80端口没有开放,然后 ...