您好,您已经在Opencv C ++中处理了来自摄像头的图像流并将其发送到c ++中的套接字服务器中;然后,我有一个javascript客户端,可以接收它并在网页中显示它,但是javascipt套接字无法连接到c ++套接字
Server.cpp
#include "opencv2/opencv.hpp"
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <unistd.h>
#include <string.h>
using namespace cv;
using namespace std;
void *display(void *);
int capDev = 0;
VideoCapture cap(capDev); // open the default camera
int main(int argc, char** argv)
{
//--------------------------------------------------------
//networking stuff: socket, bind, listen
//--------------------------------------------------------
int localSocket,
remoteSocket,
port;
int reuseaddr = 1; /* True */
struct sockaddr_in localAddr,
remoteAddr;
pthread_t thread_id;
port = atoi(argv[1]);
int addrLen = sizeof(struct sockaddr_in);
if ( (argc > 1) && (strcmp(argv[1],"-h") == 0) ) {
std::cerr << "usage: ./cv_video_srv [port] [capture device]\n" <<
"port : socket port (4097 default)\n" <<
"capture device : (0 default)\n" << std::endl;
exit(1);
}
if (argc == 2) port = atoi(argv[1]);
localSocket = socket(AF_INET , SOCK_STREAM , 0);
if (localSocket == -1){
perror("socket() call failed!!");
}
/* Enable the socket to reuse the address */
if (setsockopt(localSocket, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(int)) == -1) {
perror("setsockopt");
return 1;
}
localAddr.sin_family = AF_INET;
localAddr.sin_addr.s_addr = INADDR_ANY;
localAddr.sin_port = htons( port );
if( bind(localSocket,(struct sockaddr *)&localAddr , sizeof(localAddr)) < 0) {
perror("Can't bind() socket");
exit(1);
}
//Listening
listen(localSocket , 3);
std::cout << "Waiting for connections...\n"
<< "Server Port:" << port << std::endl;
//accept connection from an incoming client
while(1){
//if (remoteSocket < 0) {
// perror("accept failed!");
// exit(1);
//}
remoteSocket = accept(localSocket, (struct sockaddr *)&remoteAddr, (socklen_t*)&addrLen);
//std::cout << remoteSocket<< "32"<< std::endl;
if (remoteSocket < 0) {
perror("accept failed!");
exit(1);
}
std::cout << "Connection accepted" << std::endl;
pthread_create(&thread_id,NULL,display,&remoteSocket);
//pthread_join(thread_id,NULL);
}
//pthread_join(thread_id,NULL);
//close(remoteSocket);
return 0;
}
void *display(void *ptr){
int socket = *(int *)ptr;
//OpenCV Code
//----------------------------------------------------------
Mat img, imgGray;
img = Mat::zeros(480 , 640, CV_8UC1);
//make it continuous
if (!img.isContinuous()) {
img = img.clone();
}
int imgSize = img.total() * img.elemSize();
int bytes = 0;
int key;
//make img continuos
if ( ! img.isContinuous() ) {
img = img.clone();
imgGray = img.clone();
}
std::cout << "Image Size:" << imgSize << std::endl;
cap.set(CV_CAP_PROP_POS_MSEC, 300); //start the video at 300ms
double fps = cap.get(CV_CAP_PROP_FPS); //get the frames per seconds of the video
cout << "Frame per seconds : " << fps << endl;
while(1) {
/* get a frame from camera */
cap >> img;
// namedWindow( "Display window", WINDOW_AUTOSIZE );// Create a window for display.
// imshow( "Display window", img ); // Show our image inside it.
// perror("Salut!");
//
if( !img.empty() ){
//do video processing here
cvtColor(img, imgGray, CV_BGR2GRAY);
}
//send processed image
if ((bytes = send(socket, imgGray.data, imgSize, 0)) < 0){
close(socket);
std::cerr << "bytes = " << bytes << std::endl;
break;
}
// */
}
close(socket);
}
Makefile
SRCS = $(wildcard *.cpp)
PROGS = $(patsubst %.cpp,%,$(SRCS))
OBJS = $(SRCS:.cpp=.o)
TEMPS = $(SRCS:.cpp=.txt)
CFLAGS = -std=c++11 `pkg-config --cflags opencv`
LDFLAGS = `pkg-config --libs opencv`
all: $(PROGS)
%: %.cpp
g++ $(CFLAGS) -o $@ $< $(LDFLAGS) -lpthread
receptor.html
var img;
function init() {
img = document.getElementById('frame');
}
$(document).ready(function (){
init();
});
if ('WebSocket' in window) {
connect('ws://localhost:2346');
} else {
console.log('web sockets not suported');
}
var ws;
function connect(host) {
ws = new WebSocket(host);
ws.onopen = function () {
console.log('connected');
}
ws.onmessage = function (evt) {
if (evt.data != null) {
//if ((evt.data[0] == 'd') && (evt.data[1] == 'a'))
console.log(evt.data);
img.src = evt.data;
}
}
//ws.onclose = function () {
// console.log('closed');
//}
ws.onerror = function(evt) {
console.log('<span style="color: red;">ERROR:</span> ' + evt.data);
}
ws.onclose = function (event) {
var reason;
alert(event.code);
// See http://tools.ietf.org/html/rfc6455#section-7.4.1
if (event.code == 1000)
reason = "Normal closure, meaning that the purpose for which the connection was established has been fulfilled.";
else if(event.code == 1001)
reason = "An endpoint is \"going away\", such as a server going down or a browser having navigated away from a page.";
else if(event.code == 1002)
reason = "An endpoint is terminating the connection due to a protocol error";
else if(event.code == 1003)
reason = "An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).";
else if(event.code == 1004)
reason = "Reserved. The specific meaning might be defined in the future.";
else if(event.code == 1005)
reason = "No status code was actually present.";
else if(event.code == 1006)
reason = "The connection was closed abnormally, e.g., without sending or receiving a Close control frame";
else if(event.code == 1007)
reason = "An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message).";
else if(event.code == 1008)
reason = "An endpoint is terminating the connection because it has received a message that \"violates its policy\". This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy.";
else if(event.code == 1009)
reason = "An endpoint is terminating the connection because it has received a message that is too big for it to process.";
else if(event.code == 1010) // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead.
reason = "An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake. <br /> Specifically, the extensions that are needed are: " + event.reason;
else if(event.code == 1011)
reason = "A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.";
else if(event.code == 1015)
reason = "The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).";
else
reason = "Unknown reason";
$("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was closed for reason: " + reason);
};
}
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<img src="" id="frame" style="width: 240px; height: 400px" />
<div id="log"></div>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="receptor.js"></script>
</body>
</html>
谢谢您的帮助!
receptor.js