通过SOCKET发送文件

时间:2012-11-03 19:21:07

标签: c# c++ actionscript-3 flex winapi

我正在创建简单的Socket服务器。 Flex应用程序将是此服务器的客户端。在特殊要求下,我需要通过套接字将图像文件(jpeg)从服务器传输到客户端。

我已经在C#上编写了服务器用于测试目的 - 它适用于我的flex应用程序。

C#代码,发送图片:

private void sendImage(Socket client)
        {
            Bitmap data = new Bitmap("assets/sphere.jpg");
            Image img = data;
            MemoryStream ms = new MemoryStream();
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] buffer = ms.ToArray();
            sendInt(client, buffer.Length);
            client.Send(buffer);
            Console.WriteLine("Image sent");
        }

C ++代码,它发送相同的图像:

void SocketServer::sendFile(SOCKET &client, std::string filename)
{
    std::ifstream file (filename, std::ios::ate);
    if (file.is_open())
    {
        std::ifstream::pos_type size = file.tellg();
        char * memblock = new char [size];
        file.seekg (0, std::ios::beg);
        file.read (memblock, size);
        file.close();
        sendInt(client, size);
        send(client, memblock, size, 0);
        delete[] memblock;
    }
}

send方法返回正确的图像大小作为发送值。

出于某种原因,我无法在Windows 8上的Adobe Flash Builder 4.6中进行调试,因此我创建了输出小部件,我可以将传输结果视为字符串

C#转移结果: enter image description here

C ++转移结果: enter image description here

正如您所看到的,500个左右的第一个字符是相同的。 C ++的其余部分是'i'符号。奇怪的是,如果我使用此代码将文件读入字符串,例如:

std::ifstream ifs("sphere.jpg");
std::string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());

我的字符串将是~500个字符而不是124K字节(~124k字符,图像文件大小)。

这是C ++图像结果: enter image description here

所以我真的不知道为什么套接字仅正确传输jpeg的一小部分而其余部分是错误的?正如我所提到的 - 如果我将字节数组从C#传输到Flex,没有问题,所以我认为Flex方面的一切都很好。

1 个答案:

答案 0 :(得分:1)

这可能是因为您没有以二进制模式明确打开文件。尝试使用:

std::ifstream file (filename, std::ios::ate | std::ios::binary);