boost::asio 程序中的刷新缓冲区
基本上我正在使用 boost 套接字库编写一个简单的程序...我有两个程序,一个客户端和一个服务器。服务器等待来自客户端的连接,当它找到一个连接时,客户端向服务器发送一条消息,服务器打印出来,这在客户端第一次查询服务器时有效,但过了一会儿,一个奇怪的模式开始了,假设我们的服务器是运行并且我通过执行以下命令使用了客户端程序两次:
./client localhost name message
./client localhost name test
服务器的输出 0f 首先是:名称:消息
但接下来它会显示name: testage
我不知道为什么会发生这种情况,但我知道它一定是服务器的问题,因为客户端每个独立地发送一个数据包,服务器只是将其打印出来......我我认为这与套接字缓冲区没有被刷新或类似的东西有关......
无论如何,这是源代码: 客户端.cpp
http://pastebin.com/hWpLNqnW
服务器.cpp
http://pastebin.com/Q4esYwdc
Basically I am writing a simple program using the boost socket library... I have two programs a client and a server. the server waits for a connection from the client and when it finds one the client sends the server a message and the server prints out, this works the first time the client queries the server but after a while an strange pattern begins lets say our server was running and I used the client program two times by executing:
./client localhost name message
./client localhost name test
the output 0f the server would first be:name: message
however next it would displayname: testage
I don't know why this is happening but I know it must be the server, because the the clients each send a packet independently the server just prints it out... I'm thinking that this has something to do with the socket buffer not being flushed or something of that nature...
anyway heres the sourcecode:
client.cpp
http://pastebin.com/hWpLNqnW
server.cpp
http://pastebin.com/Q4esYwdc
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
服务器中的
read_some
调用返回读取的字节数。您应该使用该值并用它来终止缓冲区。沿着这些思路:在第一条消息中,缓冲区可能已用零初始化。但下一次,它将包含与上一次迭代相同的内容。请注意,
strcpy(buf,"");
调用最终只会将buf
的第一个字节设置为零。The
read_some
call in the server returns the number of bytes read. You should use that value and use it to null terminate the buffer. Something along these lines:In the first message, the buffer may have been initialized with zeros. The next time, though, it would contain the same contents as the previous iteration. Note that the
strcpy(buf,"");
call only ends up setting the first byte ofbuf
to zero.