I am trying to implement a UDP server with C++ to receive frames from the client. I am using this question as reference. Only difference is that I have a Java Client that sends the frames via udp:
Java client that sends image via UDP:
byte[] buffer = GetImageByte(FrameData,384,288,false); //GetImageByte is a function that returns a raw frame
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("127.0.0.1");
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, IPAddress, 9999);
clientSocket.send(packet);
C++ server that receives udp image:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.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>
#include <iostream>
using namespace cv;
using namespace std;
void error(const char *msg)
{
perror(msg);
exit(1);
}
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[1024];
struct sockaddr_in serv_addr, cli_addr;
int n;
int height = 384;
int width= 288;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(9999);
Mat img = Mat::zeros( height,width, CV_8UC3);
int imgSize = img.total()*img.elemSize();
uchar sockData[imgSize];
int bytes = 0;
for (int i = 0; i < imgSize; i += bytes) {
if ((bytes = recv(sockfd, sockData +i, imgSize - i, 0)) == -1) {
break;
}
}
int ptr=0;
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
img.at<cv::Vec3b>(i,j) = cv::Vec3b(sockData[ptr+ 0],sockData[ptr+1],sockData[ptr+2]);
ptr=ptr+3;
}
}
Mat image(384,288,CV_8UC3,*buffer);
close(newsockfd);
close(sockfd);
imshow( "Server", image);
waitKey(0);
return 0;
}
What I am trying to do is simply receive a frame and show it using OpenCV. The problem is that the code compiles successfully but no errors or any helpful message is shown in the console whatsoever. I tested sending the image to a UDP server in Python it works. I'd like to know how can I receive a frame via UDP using C++ and show it on screen using OpenCv?