我正在尝试通过网络将图像(使用IlpImage库)发送到VLan(媒体播放器),以便它可以播放流式图像并“制作”视频。
我正在尝试打开一个套接字,但“serversock”的值总是给我-1,我不明白为什么。我正在尝试搜索此错误但无法找到解决方案。有人能帮助我吗?
以下是代码:
#include <stdio.h>
#include <stdlib.h>
#include <direct.h>
#include <iostream>
#include <WinSock2.h>
#include <Windows.h>
#include <iostream>
#include <string.h>
#include <time.h>
#include <errno.h>
//#include <fstream>
//#include "Packet.h"
#include <opencv2/core/core.hpp> // Basic OpenCV structures (cv::Mat, Scalar)
#include <opencv2/highgui/highgui.hpp> // OpenCV window I/O
using namespace std;
#define PORT 8888
#define GROUP "127.0.0.1"
int serversock, clientsock;
int is_data_ready = 0;
//methods
void quit(char* msg, int retval);
void sendImg (IplImage *img);
void sendImg(IplImage *img) {
struct sockaddr_in server;
int opt = 1;
/* setup server's IP and port */
memset(&server,0,sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr(GROUP);
server.sin_port = htons(PORT);
//serversock = socket(AF_INET, SOCK_STREAM, 0);
serversock = socket(AF_INET, SOCK_DGRAM, 0);
虽然对serversock
的值进行重新分配应该为0并且它为-1,而不是继续该程序。
if (serversock < 0) { // or == -1
quit("socket() failed", 1);
} //else {cout<< "Consegui!" << endl
cout << "socket() succeeded" << endl;
if(setsockopt(serversock,SOL_SOCKET,SO_BROADCAST, (const char*) &opt,sizeof(int))==-1){
quit("setsockopt failed",0);
}
/*
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
server.sin_addr.s_addr = INADDR_ANY;*/
/* bind the socket */
if (bind(serversock, (const sockaddr*)&server, sizeof(server)) == -1) {
quit("bind() failed", 1);
}
/* wait for connection */
if (listen(serversock, 10) == -1) {
quit("listen() failed.", 1);
}
/* accept a client */
if ((clientsock = (int)accept(serversock, NULL, NULL)) == -1) {
quit("accept() failed", 1);
}
/* the size of the data to be sent */
int imgsize = img->imageSize;
int bytes=0;
//start sending images
if (is_data_ready) {
is_data_ready = 0;
if( (bytes = sendto(serversock, img->imageData, imgsize, 0, (struct sockaddr*)&server, sizeof(server)) ) == -1) {
quit("sendto FAILED", 1);
}
}
}
答案 0 :(得分:1)
使用WSAGetLastError()
确定失败的原因:
if (serversocket < 0)
{
const DWORD last_error = WSAGetLastError();
// Pass 'last_error' to either the 'quit' function
// or log it somewhere else.
}
发布的代码中不存在 WSAStartup()
,必须在使用任何套接字API函数之前调用它。