gpt4 book ai didi

c# - 通过 TCP 在 C++ 客户端/C# 服务器之间传输文件

转载 作者:可可西里 更新时间:2023-11-01 02:50:40 28 4
gpt4 key购买 nike

我目前正在尝试通过 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;
}

最佳答案

改变:

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

为此:

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 设置回开头。

关于c# - 通过 TCP 在 C++ 客户端/C# 服务器之间传输文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43205529/

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