读取图像文件C ++并将其放在套接字上 [英] Read an image file C++ and put it on a socket
问题描述
我想在C ++中开发一个小的Web服务器,但我有一个问题,当我尝试读取图像文件,并将其写入套接字缓冲区。
我发现一个类似的函数C写的完美,我不明白为什么我的方法不工作,当我通过浏览器连接到服务器并打开一个图像文件,我得到这个输出。
图片http://127.0.0.1:7777/myimage.jpg无法显示,因为它包含错误。
这是我的方法:
std :: string
Client :: getFileContent(const std :: string& name)
{
std :: ifstream f; f.open(name.c_str(),std :: ios :: binary);
if(!f.is_open()){
return(std :: string());
} else {
f.seekg(0,std :: ios :: end);
unsigned int length = f.tellg();
f.seekg(0,std :: ios :: beg);
char * buffer = new char [length];
f.read(buffer,length);
f.close();
return(std :: string(buffer));
}
}
socket socket(使用nspr socket):
void
Socket :: send(const std :: string& s)
{
if(PR_Send(sock,s.c_str(),s.length(),0,PR_INTERVAL_NO_WAIT)== -1){
throw(Exception :: Exception :Exception :: SOCKET_SEND));
}
}
这是我在web上找到的函数,i不能理解为什么这个工作完美,我的不工作Oo:
while((ret = read(file_fd,buffer,BUFSIZE ))> 0){
(void)write(fd,buffer,ret);非常感谢:)
$ b $ p < >解决方案您的问题在这里:
return(std :: string(buffer));
从 char *
创建字符串将停在第一个0字节,而图像可能包含很多。而不是返回一个字符串,返回一个向量< char>
like
return std :: vector< char>(buffer,buffer + length);
i'm trying to develop a little web server in C++ but i have a problem when i try to read an image file and write it in a socket buffer.
I found a similar function written in C that works perfectly, i cannot understand why my method doesn't work, when i connect to the server by browser and open an image file i got this output.
"The image "http://127.0.0.1:7777/myimage.jpg" cannot be displayed because it contains errors."
This is my method:
std::string
Client::getFileContent(const std::string& name)
{
std::ifstream f; f.open(name.c_str(), std::ios::binary);
if( !f.is_open() ) {
return (std::string(""));
} else {
f.seekg(0, std::ios::end);
unsigned int length = f.tellg();
f.seekg(0, std::ios::beg);
char* buffer = new char[length];
f.read(buffer, length);
f.close();
return ( std::string(buffer) );
}
}
And then i write it in a socket buffer(use nspr socket):
void
Socket::send(const std::string& s)
{
if(PR_Send(sock, s.c_str(), s.length(), 0, PR_INTERVAL_NO_WAIT) == -1) {
throw ( Exception::Exception(Exception::Exception::SOCKET_SEND) );
}
}
And this is the function i found on web, i cannot understand why this works perfectly and mine doesn't work O.o:
while ( (ret = read(file_fd, buffer, BUFSIZE)) > 0 ) {
(void)write(fd,buffer,ret);
Thank you very much :)
解决方案 You problem is here:
return ( std::string(buffer) );
Creating a string from a char *
will stop at the first 0 byte, while an image may contain a lot. instead of returning a string, return a vector<char>
like
return std::vector<char>(buffer, buffer + length);
这篇关于读取图像文件C ++并将其放在套接字上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!