通过TCP在C ++ Client / C#Server之间传输文件

时间:2017-04-04 11:09:25

标签: c# c++ sockets tcp winsock2

我目前正在尝试通过TCP在c ++客户端和C#服务器之间发送jpeg图片流。 我在C ++端使用transmitFile功能,但我不知道我是否在C#端正确处理它。 我没有收到运行时错误,但图片没有显示,所以我想我错过了什么。

编辑:更新了代码,我收到的fileSize正在进行stackOverflow ...

C ++代码(客户端:发送图片)

void TCPclient::sendPicture(LPCWSTR filename, std::string filename_str)
{
    HANDLE hFile = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
    //Send file size
    send(sock, (const char*)GetSize(filename_str), sizeof(int), 0);
    LogManager::log(std::to_string(GetSize(filename_str)));
    //Send file
    TransmitFile(sock, hFile, GetFileSize(hFile, NULL), 1024, NULL, NULL, TF_USE_KERNEL_APC | TF_WRITE_BEHIND);
    CloseHandle(hFile);
}

int TCPclient::GetSize(std::string filename)
{
    struct stat stat_buf;
    int rc = stat(filename.c_str(), &stat_buf);
    return rc == 0 ? stat_buf.st_size : -1;
}

C#代码(服务器:接收图片并显示)

 while (true)
        {
            try
            {
                using (MemoryStream stream = new MemoryStream(ReceiveVarData(clientSock)))
                {
                    stream.Position = 0;
                    Image image = Image.FromStream(stream);
                    if (image != null)
                        pictureBox1.Image = image;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

    public static byte[] ReceiveVarData(Socket s)
    {
        Console.WriteLine("Receiving data ...");
        int offset = 0;
        int recv;
        Console.WriteLine("Receiving data size ...");
        byte[] datasize = new byte[4];
        s.Receive(datasize);
        int size = BitConverter.ToInt32(datasize, 0);
        Console.WriteLine("Data size " + size);
        byte[] data = new byte[size];
        while (offset < size)
        {
            Console.WriteLine("Downloading " + (offset/size)*100.0 + "%");
            recv = s.Receive(data, offset, 1024, SocketFlags.None);
            if (recv == 0)
            {
                data = null;
                break;
            }
            offset += recv;
        }
        return data;
    }

1 个答案:

答案 0 :(得分:1)

更改:

using ( MemoryStream stream = new MemoryStream(ReceiveVarData(clientSock)) )
{
    stream.Position = 0;
    Image image = Image.FromStream(stream);
    if ( image != null )
        pictureBox1.Image = image;
}

对此:

Image

您在创建MemoryStream对象后立即将其丢弃 使用数据缓冲区(从我记忆中)实例化MemoryStream.Position时,会将其位置设置为该流的末尾,因此您必须将{{1}}设置回到开头。