一、发送端
#include <iostream>
#include "WinSock2.h"
#include <opencv2\opencv.hpp>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
using namespace cv;
int main()
{
char ip[20] = "192.168.50.117";
int port = 5099;
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
cout << "加载套接字失败" << endl;
return 1;
}
SOCKADDR_IN addrRec;
addrRec.sin_family = AF_INET;
addrRec.sin_port = htons(port);
addrRec.sin_addr.s_addr = inet_addr(ip);
SOCKET sockClient = socket(AF_INET, SOCK_DGRAM, 0);
if (sockClient == SOCKET_ERROR)
{
cout << "创建套接字失败" << endl;
return 1;
}
int nLen = sizeof(SOCKADDR_IN);
VideoCapture capture(0);
Mat capframe, frame;
capture >> capframe;
int framesize = sizeof(frame);
_int64 datasize = capframe.dataend - capframe.datastart;
_int64 shrinksize = datasize / 16;
cout << "============= datasize:" << datasize <<" shrinksize:"<<shrinksize<<endl;
while (capture.isOpened())
{
capture >> capframe;
int sendData;
//默认采用INTER_LINEAR双线性插值
resize(capframe, frame, Size(), 0.25, 0.25);
imshow("video", frame);
//数据长度为字节数
sendData = sendto(sockClient, (char*)frame.data, shrinksize, 0, (LPSOCKADDR)&addrRec, nLen);
if (sendData > 0)
{
//printf("size:%d,send:%d\n", shrinksize, sendData);
}
else
{
printf("发送data错误!%d %d\n", sendData, WSAGetLastError());
}
if (waitKey(20) == 27)//27是键盘摁下esc时,计算机接收到的ascii码值,然后退出
{
capture.release();
break;
}
}
WSACleanup();
return 0;
}
二、接收端
#include <iostream>
#include <thread>
#include "WinSock2.h"
#include<opencv2\opencv.hpp>
#pragma comment(lib,"ws2_32.lib")
using namespace cv;
int main()
{
char ip[20] = "192.168.50.117";
int port = 5099;
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
printf("加载套接字失败\n");
return 1;
}
SOCKADDR_IN addrRec;
addrRec.sin_family = AF_INET;
addrRec.sin_port = htons(port);
addrRec.sin_addr.s_addr = inet_addr(ip);
SOCKET sockClient = socket(AF_INET, SOCK_DGRAM, 0);
if (sockClient == SOCKET_ERROR)
{
printf("套接字创建失败\n");
return 1;
}
if (bind(sockClient, (LPSOCKADDR)&addrRec, sizeof(SOCKADDR_IN)) == SOCKET_ERROR)
{
printf("套接字绑定失败:%d\n", WSAGetLastError);
return 1;
}
SOCKADDR_IN addrSend;
int nLen = sizeof(SOCKADDR);
Mat srcframe, rsframe,frame;
VideoCapture capture(0);
capture >> srcframe;
capture.release();
resize(srcframe, frame, Size(800,600), 0, 0, INTER_AREA);
resize(srcframe, frame, Size(), 0, 0, INTER_AREA);
_int64 datasize = frame.dataend - frame.datastart;
while (1)
{
if (SOCKET_ERROR != recvfrom(sockClient, (char*)frame.data, 57600, 0, (LPSOCKADDR)&addrRec, &nLen))
{
printf("收到Data!\n");
imshow("reciver", frame);
}
if (waitKey(20) == 27)//27是键盘摁下esc时,计算机接收到的ascii码值
{
break;
}
}
WSACleanup();
return 0;
}
|