Issue
I have a React project and I am streaming a live video through websocket, but when they update the camera firmware I get an error on websocket connection.
This is how I create the WebSocket,
wsRef.current = new WebSocket(`ws://${ip}:${80}/websocket`, ["tv-img-protocol",]);
On some specific camera firmwares, I can create the WebSocket connection easily but on some firmwares I get this error message on the Network tab and I cannot create the WebSocket connection,
Error during WebSocket handshake: 'Sec-WebSocket-Protocol' header value 'text' in response does not match any of sent values
I am new to these topics so I couldn't understand the cause of this problem. When I searched online I found this: The new firmware might support different subprotocols for communication, and it's sending "text" as the preferred subprotocol in the handshake response. Does this mean I should get in touch with the camera providers and ask them to change the handshake response or is there anything I can do with my code.
Here is the whole code to create the websocket connection:
const wsRef = useRef<WebSocket | null>(null);
useEffect(() => {
wsRef.current = new WebSocket(`ws://${ip}:${80}/websocket`, [
"tv-img-protocol",
]);
wsRef.current.onopen = () => setIsLoading(false);
wsRef.current.binaryType = "arraybuffer";
wsRef.current.onmessage = function (event: MessageEvent) {
let buffer: ArrayBuffer[] = [];
let ai = 0;
let ak;
let ap = 0;
let ag = 0;
let ctr = 0;
if (event.data instanceof ArrayBuffer) {
if (event.data.byteLength !== 16000) {
ak = new Uint8Array(ap + event.data.byteLength);
for (let i = 0; i < ctr; i++) {
ak.set(new Uint8Array(buffer[i]), ag);
ag += 16000;
}
ak.set(new Uint8Array(event.data), ag);
let now = event.timeStamp;
if (imgRef.current && now >= lastTimeRef.current) {
lastTimeRef.current = now;
imgRef.current.src = "data:image/png;base64," + bytesToBase64(ak);
} else {
console.log("Timing Error on camera stream.");
}
buffer = [];
ap = 0;
ai = 0;
ag = 0;
ak = "";
} else {
buffer[ai] = event.data;
ap += event.data.byteLength;
ai++;
}
}
};
return () => {
wsRef.current?.close();
};
}, [ip]);
Solution
I added this to my code and now I can create WebSocket connection:
wsRef.current = new WebSocket(`ws://${ip}:${80}/websocket`, ["binary"]);
wsRef.current.onopen = () => {
setIsLoading(false);
wsRef.current.send("Sec-WebSocket-Protocol: tv-img-protocol\r\n\r\n");
};
Answered By - betty
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.