升压ASIO - 单独的数据不同的块 [英] Boost asio - separate different chunks of data

查看:108
本文介绍了升压ASIO - 单独的数据不同的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们创建简单的客户端 - 服务器应用从客户端发送文件到服务器。我们使用升压ASIO。

服务器开始监听。客户端连接到服务器。客户端发送文件名和文件的内容。

但服务器接收只是一个字节流。如何服务器能够检测到文件末尾和文件内容开始?

第一个想法我已经是使用特殊的分隔符。客户端写入到套接字文件名,然后分隔符,然后文件的内容。服务器使用'read_until接收文件名和读来读取文件内容。

这是一个好的解决方案吗?

如果我要送10个文件连续什么 - 搜索的字节流中的分隔符可以是昂贵的...


解决方案

  

第一个想法我已经是使用特殊的分隔符。


这是正确的方式。这是你的协议的责任。和协议可以定义长度的头,或特殊的分隔符。

长头是二进制协议更常见(BSON一样)。

特殊分隔符文本的协议是共同的。


  

客户端写入到套接字文件名,然后分隔符,然后文件的内容。


  
  

服务器使用'read_until接收文件名和读来读取文件内容。


  
  

这是一个好的解决方案吗?


是的。只要你记得 read_until 读取直到收到一个数据包,它包含的分隔符。我可以读取 更多,所以你可能已经在同一时间的内容(部分)。

参见:<一href=\"http://stackoverflow.com/questions/33629567/missing-the-first-characters-using-boostasiostreambuf-probably-fixed/33630386#33630386\">Missing使用boost :: ASIO ::流缓冲的第一个字符 - 大概固定

Imagine we create simple client-server app to send files from client to server. We use boost asio.

Server starts listening. Client connects to the server. Client send filename and file content.

But server receive just a stream of bytes. How server detect end of filename and start of file content?

First idea I have is to use special delimiter. Client writes into the socket filename, then delimiter, then file content. Server uses 'read_until' to receive filename and 'read' to read file content.

Is it a good solution?

What if I want to sent 10 files in a row - searching for delimiter in the byte stream may be expensive...

解决方案

First idea I have is to use special delimiter.

That's the right way. It's the responsibility of your protocol. And the protocol may define length headers, or special delimiters.

Length headers are more common in binary protocols (BSON-like).

Special delimiters are common in text protocols.

Client writes into the socket filename, then delimiter, then file content.

Server uses 'read_until' to receive filename and 'read' to read file content.

Is it a good solution?

Yes. As long as you remember that read_until reads until a packet is received that contains the delimiter. I may read more, so you might already have (part) of the content at the same time.

See also: Missing the first characters using boost::asio::streambuf - Probably fixed

这篇关于升压ASIO - 单独的数据不同的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆