[英]C++ socket only sends first 4 bytes of data
我目前正在使用C ++ for Linux编写套接字包装。 它基本上是处理TCP套接字的创建,连接,发送,读取和关闭的类的集合。
在我的套接字类中,除发送和接收功能外,所有功能均正常运行。 他们不返回错误; 相反,它仅发送数据的前四个字节。
我的发送功能:
int Socket::sends(char* buffer){
int bytes; // for number of bytes sent
/* First, send the size of buffer */
int datalen = strlen(buffer); // get sizeof buffer
int len = htonl(datalen); // reformat
// send the size of the buffer
bytes = send(socketfd, (char*)&len, sizeof(len), 0); // send the size
if (bytes < 0){
cerr << "Error sending size of buffer to socket" << endl;
return 1;
}
/* Now acutally send the data */
bytes = send(socketfd, buffer, datalen, 0);
if (bytes < 0){
cerr << "Error writing buffer to socket" << endl;
return 1;
}
cout << bytes << " written" << endl;
return 0;
}
其背后的思想是,它先发送缓冲区的大小,然后再发送实际的缓冲区,从而发送缓冲区( char* buffer
)。 如果遇到错误(返回-1),该函数将通过返回1终止。
现在,这是read方法:
int Socket::reads(char* buffer){
int bytes, buflen; // for bytes written and size of buffer
/* Read the incoming size */
bytes = recv(socketfd, (char*)&buflen, sizeof(buflen), 0);
if (bytes < 0){
cerr << "Error reading size of data" << endl;
return 1;
}
buflen = ntohl(buflen);
/* Read the data */
bytes = recv(socketfd, buffer, buflen, 0);
if (bytes < 0){
cerr << "Error reading data" << endl;
return 1;
}
return 0;
}
这里的想法是先读取数据的大小,然后将缓冲区设置为该大小并读入其中。 该函数在出错时返回1(recv返回-1)。
使用方法看起来像这样:
socket.sends("Hello World"); // socket object sends the message
char* buffer;
socket.reads(buffer); // reads into the buffer
但是,无论何时使用这些功能,我只会收到前4个字节的数据,后跟奇怪的非ASCII字符。 我不知道为什么会这样。 在send
和recv
函数中没有遇到错误,并且函数说只写入了4个字节。 有没有更好的方式发送或接收数据? 我忽略了一个非常简单的错误?
谢谢你的帮助!
您正在将未初始化的指针( buffer
)传递给reads
方法,这可能解释了它部分起作用(未定义的行为)。
而且,您不应该将buffer
作为参数传递,因为它不会被修改(而且您仍然不知道大小)
另外,您必须在收到消息时以零结尾。
我会这样:
char *Socket::reads(){
char* buffer;
int bytes, buflen; // for bytes written and size of buffer
/* Read the incoming size */
bytes = recv(socketfd, (char*)&buflen, sizeof(buflen), 0);
if (bytes < 0){
cerr << "Error reading size of data" << endl;
return 1;
}
buflen = ntohl(buflen);
buffer = new char[buflen+1]; // +1 for the NUL-terminator
/* Read the data */
bytes = recv(socketfd, buffer, buflen, 0);
if (bytes < 0){
cerr << "Error reading data" << endl;
return 1;
}
buffer[buflen] = '\0'; // NUL-terminate the string
return buffer;
}
主要的:
socket.sends("Hello World"); // socket object sends the message
char* buffer = socket.reads(); // reads into the buffer
不要忘记最后delete []
缓冲区。
也可以使用std::string
或std::vector<char>
来完成,以免new
和delete
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.