Unpacking BLOB from websocket - javascript

While using websocket, message that client gets is blob. Whats the best way to access its content? I have tried using FileReader but then it looked like {"user":"whatever","msg":"whatever"} and I would like to get it as {user:"whatever",msg:"whatever"}. Is it even possible?
const submitMessage = (usr, msg) => {
const message = { user: loggedInUser.username, message: msg };
ws.send(JSON.stringify(message));
setMessages([message, ...messages]);
}
useEffect(() => {
ws.onopen = () => {
console.log('WebSocket Connected');
}
ws.onmessage = (e) => {
const message = JSON.parse(e.data);
setMessages([message, ...messages]);
}
return () => {
ws.onclose = () => {
console.log('WebSocket Disconnected');
setWs(new WebSocket(URL));
}
}
}, [ws.onmessage, ws.onopen, ws.onclose, messages]);
**server**
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(data) {
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(data);
}
});
});
});

Related

onclose, onopen, onerror not work in sockjs with typescript

i'm listen websocket with sockjs in typescript and angular
my code:
webSocketOpen() {
let ws = new SockJS('http://localhost:8081/chat', null, { timeout: 6000 });
ws.onopen = () => {
console.log('a');
}
ws.onclose = () => {
console.log('b');
}
ws.onerror = () => {
console.log('c');
}
this.stompClient = Stomp.over(ws);
let that = this;
this.stompClient.connect({}, () => {
that.stompClient.subscribe("/topic/messages", (message) => {
console.log(message.body);
}, (error) => {
console.log('error');
}
);
});
}
but onclose in sockjs doesn't work when connection to server is close or connection disconnected. as well as other method onopen, onerror. please help me how to know that the websocket is disconnected or connected?

ReactJs : WebSocket is closed before the connection is established

Full-Stack Web Application using React, Node Js, Web sockets. My project is based on ReactJs with server on Express. When trying to connect to socket.io from chrome I receive "WebSocket is closed before the connection is established" message.
"editorpage.js"
useEffect(() => {
const init = async () => {
socketRef.current = await initSocket();
socketRef.current.on('connect_error', (err) => handleErrors(err));
socketRef.current.on('connect_failed', (err) => handleErrors(err));
function handleErrors(e) {
console.log('Socket Error', e);
toast.error('Socket Connection Failed, Try Again Later.');
reactNavigator('/');
}
socketRef.current.emit(ACTIONS.JOIN, {
roomId,
username: location.state?.username,
});
// Listening for joined event
socketRef.current.on(
ACTIONS.JOINED,
({ clients, username, socketId }) => {
if (username !== location.state?.username) {
toast.success(`${username} joined the room.`);
console.log(`${username} joined`);
}
setClients(clients);
socketRef.current.emit(ACTIONS.SYNC_CODE, {
code: codeRef.current,
socketId,
});
}
);
// Listening for disconnected
socketRef.current.on(
ACTIONS.DISCONNECTED,
({ socketId, username }) => {
toast.success(`${username} left the room.`);
setClients((prev) => {
return prev.filter(
(client) => client.socketId !== socketId
);
});
}
);
};
init();
return () => {
socketRef.current?.disconnect();
socketRef.current?.off(ACTIONS.JOINED);
socketRef.current?.off(ACTIONS.DISCONNECTED);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
This error when running on google chrome
"socket.js"
import { io } from 'socket.io-client';
export const initSocket = async () => {
const options = {
'force new connection': true,
reconnectionAttempt: 'Infinity',
timeout: 10000,
transports: ['websocket'],
};
return io(process.env.REACT_APP_BACKEND_URL, options);
};
"server.js"
const express = require('express');
const app = express();
const http = require('http');
const {
Server
} = require('socket.io');
const ACTIONS = require('./src/Actions');
const server = http.createServer(app);
const io = new Server(server);
const userSocketMap = {};
function getAllConnectedClients(roomId) {
// Map
return Array.from(io.sockets.adapter.rooms.get(roomId) || []).map(
(socketId) => {
return {
socketId,
username: userSocketMap[socketId],
};
}
);
}
io.on('connection', (socket) => {
console.log('socket connected', socket.id);
socket.on(ACTIONS.JOIN, ({
roomId,
username
}) => {
userSocketMap[socket.id] = username;
socket.join(roomId);
const clients = getAllConnectedClients(roomId);
clients.forEach(({
socketId
}) => {
io.to(socketId).emit(ACTIONS.JOINED, {
clients,
username,
socketId: socket.id,
});
});
});
socket.on(ACTIONS.CODE_CHANGE, ({
roomId,
code
}) => {
socket.in(roomId).emit(ACTIONS.CODE_CHANGE, {
code
});
});
socket.on(ACTIONS.SYNC_CODE, ({
socketId,
code
}) => {
io.to(socketId).emit(ACTIONS.CODE_CHANGE, {
code
});
});
socket.on('disconnecting', () => {
const rooms = [...socket.rooms];
rooms.forEach((roomId) => {
socket.in(roomId).emit(ACTIONS.DISCONNECTED, {
socketId: socket.id,
username: userSocketMap[socket.id],
});
});
delete userSocketMap[socket.id];
socket.leave();
});
});
const PORT = process.env.PORT || 5001;
server.listen(PORT, () => console.log(`Listening on port ${PORT}`));

mongoDB changestream emitting multiple times nodejs

What could be the reason that change event is getting called so many times while all I am doing is basic crud on the document ? If change in document then I am refreshing my table by calling serverSideListProject API. and Also, I noticed that connection is getting disconnect frequently, is there any configurations we can make to stop it from disconnecting ?
"socket.io": "^2.2.0" for server-side,"ngx-socket-io": "^3.4.0" for client.
app.module.js:
import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
const config: SocketIoConfig = { url: 'http://localhost:6001', options: {} };
DBHandler code:
exports.monitorChanges = function () {
return new Promise((resolve, reject) => {
return getConnection().then((db) => {
if (db == null) {
console.log("db in find() is undefined");
reject();
} else {
const changeStream = db.db(config.mongodb.dbname).collection("project").watch(
[
{ $match: { "operationType": { $in: ["insert", "update", "replace"] } } },
{ $project: { "_id": 1, "fullDocument": 1, "ns": 1, "documentKey": 1 } }
],
{ fullDocument: "updateLookup" }
);
resolve(changeStream)
}
socket connection:
route.js
var express = require('express');
var app = express();
const io = require('socket.io')();
io.on('connection', socket => {
console.log('connected', socket.id)
socket.on('projects', (data) => projectHandler.serverSideListProject(socket, data));
socket.on('addProject', (data) => projectHandler.addProject(socket, data));
socket.on('updateProject', (data) => projectHandler.updateProject(socket, data));
socket.on('deleteProject', (data) => projectHandler.deleteProject(socket, data));
socket.on('disconnect', () => console.log('A user disconnected'));
});
io.on("connect_error", (err) => { console.log(`connect_error due to ${err.message}`) });

Node websockets missing reason in close event

I'm developing a websocket server with Node.Js v14.17.3 using "ws": "^7.4.5" package.
My server code is this:
const WebSocket = require("ws");
const url = "localhost";
const port = 8081;
const wss = new WebSocket.Server({ host: url, port });
wss.on("connection", function (ws) {
ws.on("message", function (data) {
console.log("received: %s", data);
});
function onSocketClose(code, reason) {
console.log("Closing open web socket", code, reason);
console.log("Closed web socket.");
}
ws.on("close", onSocketClose);
});
My client code is this:
window.onclose = function (event) {
console.log("Window closing.");
closeSocket("Window closed");
};
window.onunload = function (event) {
console.info("Window unloaded");
closeSocket("Window unloaded");
};
function closeSocket(reason) {
if (reason) {
console.info("Closing socket due to:", reason);
} else {
reason = "Unknown reason";
}
webSocket.onclose = function (ev) {
console.info("Websocket closed.");
};
webSocket.close(1001, reason);
}
In server on("close", ...) callback I get an empty reason, while I'm expecting the reason I've specified in client method.

Getting WebSockets to Work with Nginx and Asp.Net Core on Raspberry Pi

I am trying to get web sockets working inside a Asp.Net Core app that is hosted under nginx inside Raspberry Pi.
My default file settings are:
location /the_socket/ {
proxy_pass http://websocket:8090/;
}
in class the websocket (using Fleck) is opened like:
var server = new WebSocketServer("ws://0.0.0.0:8090/the_socket");
server.Start(
socket =>
{
socket.OnOpen = () =>
{
};
socket.OnClose = () =>
{
};
socket.OnMessage = message =>
{
};
});
This is my calling JavaScript:
url = "ws://the_socket:8090";
$(document).ready(function () {
function Connect() {
try {
$("#lblConnectionStatus").html("Reconnecting...");
if (ws instanceof WebSocket) {
ws.close();
}
ws = new WebSocket(url);
ws.binaryType = "arraybuffer";
ws.onerror = function (e) {
$("#divInternalMessangingStatus").html("Internal Messaging Error: " + e.message);
};
ws.onclose = function () {
$("#divInternalMessangingStatus").html("Internal Messaging Closed:");
Connect();
};
ws.onopen = function () {
$("#divInternalMessangingStatus").html("Client connected");
};
ws.onmessage = function (e) {
$("#divInternalMessangingStatus").html(e.data);
};
} catch (err) {
$("#divInternalMessangingStatus").html(err);
}
}
Connect();
});
Which errors on Connection Refused...
NB
I had tried changing:
location /the_socket/ {
proxy_pass http://websocket:8090/;
}
to:
location /the_socket/ {
proxy_pass http://0.0.0.0:8090/;
}

Categories