gpt4 book ai didi

c++ - 将 "binary string"转换为 "const char*"以发送(网络服务器)

转载 作者:可可西里 更新时间:2023-11-01 16:56:38 24 4
gpt4 key购买 nike

我想用函数send()发送二进制数据

功能:

void ssend(const char* data){
send(socket_fd, data, strlen(data), 0);
}

bool readFile(const char* path){
std::ifstream ifile(path);
if(ifile){
if(!ifile.is_open()){
ErrorPage("403");
return true;
}
std::string sLine;

std::string Header = "HTTP/1.1 200 OK\nConnection: Keep-Alive\nKeep-Alive: timeout=5, max=100\nServer: BrcontainerSimpleServer/0.0.1 (Win32) (Whitout Compiler code)\n\n";
ssend(Header.c_str());

while(!ifile.eof()){
getline(ifile, sLine);
cout << "String: " << sLine << endl;
cout << "const char*: " << sLine.c_str() << endl;

ssend(sLine.c_str());
}
return true;
}
return false;
}

测试:

...
while (1) {
socket_fd = accept(listen_fd, (struct sockaddr *)&client_addr,&client_addr_length);
readFile( httpPath );
recv(socket_fd, request, 32768, 0);
closesocket(socket_fd);
}
...

当使用.c_str() 转换为二进制字符串 时,数据会消失。如何解决这个问题?

如何使用函数send()发送二进制数据

最佳答案

在 C 和 C++ 中,字符串以零值字符 ('\0') 结束。因此,当您说“二进制字符串”时,您是在混合一些不相干的东西,因为二进制数据与字符串不同。

不使用字符串,而是使用 BYTE 数组并将长度作为附加参数传递,以便您知道要发送多少字节。

一旦遇到字符串终止符,您对 strlen() 的使用将停止计数。

关于c++ - 将 "binary string"转换为 "const char*"以发送(网络服务器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14131231/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com