C ++套接字256字节缓冲区 [英] C++ socket 256 byte buffer

查看:144
本文介绍了C ++套接字256字节缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在C ++中使用一些套接字网络编程。我试图发送文本Hello World!到使用C ++ send()函数的服务器。首先,我将缓冲区设置为13的大小,因为Hello World!总共是12个字符(你必须使它比字符计数多一个)。发送函数只发送字符到服务器,如果我发送它约7次。当它终于来到服务器,它看起来像这样:

I am trying to use some socket network programming in C++. I am trying to send the text "Hello World!" to a server using the C++ send() function. At first, I set the buffer to the size of 13 since "Hello World!" altogether is 12 characters (you have to make it one more than the character count). The send function only sends the characters to the server if I send it about 7 times. And when it does finally come to the server it looks like this:

Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World! !

"Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World!"

现在这里是有趣的部分。 Hello World!如果我将缓冲区大小设置为256(字符缓冲区[256];),则立即发送。当谈到这样的服务器,它显示Hello World!与一大堆空间后两个字。为什么会发生这种情况,如果可能,我该如何解决呢?

Now here is the funny part. The "Hello World!" sentence sends immediately if I set the buffer size to 256 (char buffer[256];). When it comes to the server like that though, it shows "Hello World!" with a whole bunch of space after the two words. Why is this happening and if possible, how can I fix it? Please let me know.

感谢

推荐答案

code> read (或 receive )从缓冲区读取套接字,返回一个整数值,指定字节数读。你应该只从缓冲区取得那么多。其余的是无关的:

When you call read (or receive) with your buffer to read from the socket, an integer value is returned that specifies the number of bytes read. You should only take that much from the buffer. The rest is irrelevant:

int count = read(...);
// buffer[0 .. count - 1] contains the appropriate data.

这篇关于C ++套接字256字节缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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