0

我正在尝试通过网络将图像(使用 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);
        }
    }
}
4

1 回答 1

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 函数之前调用它。

于 2013-04-30T11:15:35.757 回答