我已经从答案帖子 here 中改编了这段代码将图像保存到缓冲区中。现在我想通过 UDP 数据包发送此缓冲区。我对如何使用感到困惑 套接字中的 sendto() 函数。感谢您提供的任何帮助。
{
IStream *pStream = NULL;
LARGE_INTEGER liZero = {};
ULARGE_INTEGER pos = {};
STATSTG stg = {};
ULONG bytesRead=0;
HRESULT hrRet=S_OK;
BYTE* buffer = NULL; // this is your buffer that will hold the jpeg bytes
DWORD dwBufferSize = 0; // this is the size of that buffer;
hrRet = CreateStreamOnHGlobal(NULL, TRUE, &pStream);
//hrRet = pScreenShot->Save(pStream, &imageCLSID, &encoderParams) == 0 ? S_OK : E_FAIL;
bitmap.Save(pStream, &clsid, &encoderParameters);
hrRet = pStream->Seek(liZero, STREAM_SEEK_SET, &pos);
hrRet = pStream->Stat(&stg, STATFLAG_NONAME);
// allocate a byte buffer big enough to hold the jpeg stream in memory
buffer = new BYTE[stg.cbSize.LowPart];
hrRet = (buffer == NULL) ? E_OUTOFMEMORY : S_OK;
dwBufferSize = stg.cbSize.LowPart;
// copy the stream into memory
hrRet = pStream->Read(buffer, stg.cbSize.LowPart, &bytesRead);
// now go save "buffer" and "dwBufferSize" off somewhere. This is the jpeg buffer
// don't forget to free it when you are done
// After success or if any of the above calls fail, don't forget to release the stream
if (pStream)
{
pStream->Release();
}
}
最佳答案
请在下面找到使用 sendto()
通过 UDP 发送数据的代码,您只需要添加您的代码
用于读取图像并将其存储在缓冲区中(我已经在下面的代码中提到了添加代码的位置)。请不要在 c
中编写此代码,所以在你身边你需要一些来自 的对话c
到 c++
。
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/time.h>
#define REMOTE_SERVER_PORT 1501
#define MAX_MSG 100
int main(int argc, char *argv[]) {
int sd, rc, i;
struct sockaddr_in cliAddr, remoteServAddr;
struct hostent *h;
FILE* filein;
long lSize;
char *buffer;
/* get server IP address (no check if input is IP address or DNS name */
h = gethostbyname(argv[1]);
if(h==NULL) {
printf("%s: unknown host '%s' \n", argv[0], argv[1]);
exit(1);
}
printf("%s: sending data to '%s' (IP : %s) \n", argv[0], h->h_name,
inet_ntoa(*(struct in_addr *)h->h_addr_list[0]));
remoteServAddr.sin_family = h->h_addrtype;
memcpy((char *) &remoteServAddr.sin_addr.s_addr,
h->h_addr_list[0], h->h_length);
remoteServAddr.sin_port = htons(REMOTE_SERVER_PORT);
/* socket creation */
sd = socket(AF_INET,SOCK_DGRAM,0);
if(sd<0) {
printf("%s: cannot open socket \n",argv[0]);
exit(1);
}
/* bind any port */
cliAddr.sin_family = AF_INET;
cliAddr.sin_addr.s_addr = htonl(INADDR_ANY);
cliAddr.sin_port = htons(0);
rc = bind(sd, (struct sockaddr *) &cliAddr, sizeof(cliAddr));
if(rc<0) {
printf("%s: cannot bind port\n", argv[0]);
exit(1);
}
//please put Here your code to read image and store it in buffer
// send data
rc = sendto(sd, buffer, sizeof(buffer)+1, 0,
(struct sockaddr *) &remoteServAddr,
sizeof(remoteServAddr));
if(rc<0) {
printf("%s: cannot send data %d \n",argv[0],i-1);
close(sd);
exit(1);
}
return 1;
}
关于c++ - 在 C++ 中通过 UDP 发送缓冲图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21642135/