Skip to content

Instantly share code, notes, and snippets.

@panqiincs
Last active April 22, 2022 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save panqiincs/eb7d8c2e8fdb9c7ac19695f019e9e899 to your computer and use it in GitHub Desktop.
Save panqiincs/eb7d8c2e8fdb9c7ac19695f019e9e899 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#define oops(msg) {perror(msg); exit(1);}
int main(int argc, char *argv[])
{
struct sockaddr_in saddr;
struct hostent *hp;
int sock;
if (argc < 3) {
fprintf(stderr, "ERROR, no port provided");
exit(1);
}
hp = gethostbyname(argv[1]);
if (hp == NULL) {
oops("no such computer");
}
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
oops("socket");
}
bzero(&saddr, sizeof(saddr));
bcopy(hp->h_addr, (struct sockaddr *)&saddr.sin_addr, hp->h_length);
saddr.sin_family = AF_INET;
saddr.sin_port = htons(atoi(argv[2]));
if (connect(sock, (struct sockaddr *)&saddr, sizeof(saddr)) != 0) {
oops("connect");
}
cv::namedWindow("Display image", cv::CV_WINDOW_AUTOSIZE);
char data_size_str[20] = {0};
for (;;) {
recv(sock, data_size_str, 15, 0); // 读取数据的大小
int framelen = atoi(data_size_str); // 文本转化成int
// 接收压缩后的图像数据
std::vector<uchar> buff(framelen);
int bytes = 0;
for (int i = 0; i < framelen ; i += bytes) {
if ((bytes = recv(sock, &buff[0]+i, framelen-i, 0)) == -1) {
oops("Receive");
}
}
// 解压图像
cv::Mat frame = cv::imdecode(cv::Mat(buff), cv::CV_LOAD_IMAGE_COLOR);
cv::imshow("Display image", frame);
cv::waitKey(20);
}
close(sock);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment