你好,我照着您的https://blog.csdn.net/qq_43747351/article/details/118935168
这是python代码
import asyncio
import websockets
import base64
from cv2 import cv2
import numpy as np
import configparser
#pip install websockets
capture = cv2.VideoCapture(0, cv2.CAP_DSHOW)
if not capture.isOpened():
print('no video')
quit()
ret, frame = capture.read()
encode_param=[int(cv2.IMWRITE_JPEG_QUALITY),80]
#Send image to node server
async def send_msg(websocket):
global ret,frame
while ret:
result, imgencode = cv2.imencode('.jpg', frame, encode_param)
data = np.array(imgencode)
#img = data.tostring()
img = data.tobytes()
img = base64.b64encode(img).decode()
await websocket.send("data:image/jpeg;base64," + img)
# img = data.tobytes()
# await websocket.send(img)
ret, frame = capture.read()
async def main():
cf = configparser.ConfigParser()
cf.read("config.ini")
WS_HOST = cf.get("websocket", "host")
PORT = cf.get("websocket", "port")
WS_URL = 'ws://'+WS_HOST+':'+str(PORT)
print(WS_URL)
async with websockets.connect(WS_URL) as websocket:
await send_msg(websocket)
asyncio.get_event_loop().run_until_complete(main())
这是serer.js代码
let WebSocketServer = require('ws').Server,
wss = new WebSocketServer({ port: 8188});
wss.on('connection', function (ws) {
console.log('客户端已连接');
ws.on('message', function (message) {
wss.clients.forEach(function each(client) {
client.send(message);
});
//console.log(message.length);
});
});
这是html代码
html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>测试title>
<script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.3.1/jquery.min.js">script>
head>
<body>
<div>
<img id="resImg" src="" />
div>
<p>测试视频p>
<script>
let ws = new WebSocket("ws://127.0.0.1:8188/");
ws.onopen = function(evt) {
console.log("Connection open ...");
ws.send("Hello WebSockets!");
};
ws.onmessage = function(evt) {
console.log(evt.data)
$("#resImg").attr("src",evt.data);
console.log( "Received Message: " + evt.data);
// ws.close();
};
ws.onclose = function(evt) {
console.log("Connection closed.");
};
script>
body>
html>
```
看你浏览器的请求网络 格