I am facing an issue with Websocket in Next js
I am building a chat module when send short messages it works correctly but when i send longer messages such as messages that have more than 278 characters precisely the connection get closed cleanly with status code 1011 and no reason given.
this is how I making connection with Websocket:
'use client';
import { useEffect, useRef } from 'react';
function useConnectWebSocket(url, isChatRoom = false, chatRoomId = null) {
const socketRef = useRef(null);
useEffect(() => {
let socket;
const connect = () => {
if (isChatRoom) {
if (chatRoomId) {
socket = new WebSocket(url);
}
} else {
socket = new WebSocket(url);
}
socketRef.current = socket;
if (socket) {
socket.onopen = () => {
console.log('WebSocket connection opened');
};
socket.onerror = error => {
console.error('WebSocket error', error);
};
socket.onclose = event => {
if (event.wasClean) {
console.log('Connection closed cleanly', event);
}
};
socket.onmessage = event => {
console.log('Message from server', event.data);
};
}
};
connect();
}, [chatRoomId]);
return socketRef.current && socketRef.current;
}
export default useConnectWebSocket;
This is how i am sending the message
const payload = {
message: values?.message,
room: chatRoomId,
};
const sendMessagePayload = JSON.stringify(payload);
setPendingMessages(prevState => [...prevState, { id: v4(), ...payload }]);
socket.send(sendMessagePayload);
What I want is to connection remain open despite the length of the message.
New contributor
Haroon Shahid is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.