Different behaviour when calling emit from class methods - javascript

I am building an app with socket.io and typescript. As always I have created server and client but now I'm facing weird issue with my server code. My server is listening on 'connection' event and as callback creates new class instance and invokes his onConnect method. In this function it invokes another method - 'bindHandlers'. In this function socket listens to his events.
And this is my problem: if i pass callback to 'draw' event as an anonymous function it works as expected, but if i use my class method it sends events back to to the client instead of broadcasting it. I want to make my code more modular and this issue is blocking me for now.
main file:
io.on("connection", SocketService.createInstance(db).onConnect);
simplified socket file:
export class SocketService {
private socket: Socket | null = null;
constructor(private db: DB) {}
static createInstance = (db: DB) => {
return new SocketService(db);
};
onConnect = (socket: Socket) => {
this.socket = socket;
const username = socket.handshake.query.user;
console.log(`${username} connected ${socket.id}`);
this.bindHandlers(socket);
};
private bindHandlers = (socket: Socket) => {
if (!this.socket) return console.log("socket is undefined");
socket.on("draw", this.onDraw);
// if I swap with code below it works properly
// socket.on("draw", data => {
// socket.broadcast.emit("draw", data);
// });
};
private onDraw = (data: DrawingPoint) => {
const username = this.socket!.handshake.query.user;
const { group } = data;
this.socket!.broadcast.emit("draw", data);
};

The reason why it is working with:
socket.on("draw", data => {
socket.broadcast.emit("draw", data);
});
is because you are using arrow function which for context (this) will have surrounding context, but when defining an event handler such as: socket.on("draw", this.onDraw); context will not be anymore instance of SocketService. Play with it a little bit and debug it to see what will be the context in a case when you are calling it with that.
One solution would be to set the context explicitly such as:
socket.on("draw", this.onDraw.bind(this));
Keep in mind that context of the method/function in JS depends on how method was called.

Related

How to get "disconnecting" event Nest SocketIO

I have a problem to get all room that socket client currently in when this client disconnect, by using
async handleDisconnect(client: Socket) {
console.log(client.rooms) // result is {}
}
but Nest-SocketIO only return list rooms as {}.
As I known, in socketIO we can use:
socket.on("disconnecting", ()=>{
console.log(socket.rooms // return all room current
}
How can I use this features in NestJS-SOcketIO ?
Thanks for all.
I got this working by attaching event handler on connection.
handleConnection(client: Socket, ...args: any[]) {
this.logger.log(`Client connected: ${client.id}`);
client.on('disconnecting', (reason) => {
this.logger.log(`DISCONNECTING: ${Array.from(client.rooms)}`); // Set { ... }
});
}

How to detect which message was sent from the Websocket server

I have a small web application listening for incoming messages from a Websocket server. I receive them like so
const webSocket = new WebSocket("wss://echo.websocket.org");
webSocket.onopen = event => webSocket.send("test");
webSocket.onmessage = event => console.log(event.data);
but the sending server is more complex. There are multiple types of messages that could come e.g. "UserConnected", "TaskDeleted", "ChannelMoved"
How to detect which type of message was sent? For now I modified the code to
const webSocket = new WebSocket("wss://echo.websocket.org");
webSocket.onopen = event => {
const objectToSend = JSON.stringify({
message: "test-message",
data: "test"
});
webSocket.send(objectToSend);
};
webSocket.onmessage = event => {
const objectToRead = JSON.parse(event.data);
if (objectToRead.message === "test-message") {
console.log(objectToRead.data);
}
};
So do I have to send an object from the server containing the "method name" / "message type" e.g. "TaskDeleted" to identify the correct method to execute at the client? That would result in a big switch case statement, no?
Are there any better ways?
You can avoid the big switch-case statement by mapping the methods directly:
// List of white-listed methods to avoid any funny business
let allowedMethods = ["test", "taskDeleted"];
function methodHandlers(){
this.test = function(data)
{
console.log('test was called', data);
}
this.taskDeleted = function(data)
{
console.log('taskDeleted was called', data);
}
}
webSocket.onmessage = event => {
const objectToRead = JSON.parse(event.data);
let methodName = objectToRead.message;
if (allowerMethods.indexOf(methodName)>=0)
{
let handler = new methodHandlers();
handler[methodName](data);
}
else
{
console.error("Method not allowed: ", methodName)
}
};
As you have requested in one of your comments to have a fluent interface for the websockets like socket.io.
You can make it fluent by using a simple PubSub (Publish Subscribe) design pattern so you can subscribe to specific message types. Node offers the EventEmitter class so you can inherit the on and emit events, however, in this example is a quick mockup using a similar API.
In a production environment I would suggest using the native EventEmitter in a node.js environment, and a browser compatible npm package in the front end.
Check the comments for a description of each piece.
The subscribers are saved in a simple object with a Set of callbacks, you can add unsubscribe if you need it.
note: if you are using node.js you can just extend EventEmitter
// This uses a similar API to node's EventEmitter, you could get it from a node or a number of browser compatible npm packages.
class EventEmitter {
// { [event: string]: Set<(data: any) => void> }
__subscribers = {}
// subscribe to specific message types
on(type, cb) {
if (!this.__subscribers[type]) {
this.__subscribers[type] = new Set
}
this.__subscribers[type].add(cb)
}
// emit a subscribed callback
emit(type, data) {
if (typeof this.__subscribers[type] !== 'undefined') {
const callbacks = [...this.__subscribers[type]]
callbacks.forEach(cb => cb(data))
}
}
}
class SocketYO extends EventEmitter {
constructor({ host }) {
super()
// initialize the socket
this.webSocket = new WebSocket(host);
this.webSocket.onopen = () => {
this.connected = true
this.emit('connect', this)
}
this.webSocket.onerror = console.error.bind(console, 'SockyError')
this.webSocket.onmessage = this.__onmessage
}
// send a json message to the socket
send(type, data) {
this.webSocket.send(JSON.stringify({
type,
data
}))
}
on(type, cb) {
// if the socket is already connected immediately call the callback
if (type === 'connect' && this.connected) {
return cb(this)
}
// proxy EventEmitters `on` method
return super.on(type, cb)
}
// catch any message from the socket and call the appropriate callback
__onmessage = e => {
const { type, data } = JSON.parse(e.data)
this.emit(type, data)
}
}
// create your SocketYO instance
const socket = new SocketYO({
host: 'wss://echo.websocket.org'
})
socket.on('connect', (socket) => {
// you can only send messages once the socket has been connected
socket.send('myEvent', {
message: 'hello'
})
})
// you can subscribe without the socket being connected
socket.on('myEvent', (data) => {
console.log('myEvent', data)
})

How to use socket io inside class

I'm trying to create game using socket io. I want to implement socket inside server.js but I would like to keep events inside Room.js.:
server.js
const io = require('socket.io').listen(server)
io.sockets.on('connection', socket => {
socket.on('join room', data => {
let room = new Room(data.id, socket)
socket.join(`room${data.id}`)
}
}
Room.js
class Room{
constuctor(id, socket){
this.id = id,
this.socket = socket,
this.handlerOfEvents()
}
handlerOfEvents() {
this.socket.on('new player connected', data => {
console.log('New player connected!')
}
}
}
I tried do as above but it doesn't work:
\node_modules\has-binary2\index.js:30
function hasBinary (obj) {
^
RangeError: Maximum call stack size exceeded
Is there any solution to do sth like this?
Or maybe there is another perfect way to implement events for particular room.
This problem occurs when I try assign socket to this.socket but when I put it directly as argument like below:
class Room{
constuctor(id, socket){
this.id = id,
//this.socket = socket,
this.handlerOfEvents(socket)
}
handlerOfEvents(socket) {
socket.on('new player connected', data => {
console.log('New player connected!')
}
}
}
then just invoke this method in server.js
socket.on('joined new player', data => {
...
room.handlerOfEvents(socket)
}
so, this solution is working for now. But if this is proper way?
Issue from link in comments didn't solve my problem unfortunately.
Thanks for helping!

socket io event fires multiple times

I have searched similar questions here but none of them work for me.
I know some people recommend not to use socket inside another event but I had no clue how to trigger socket whenever there is an event.
So I have initialized socket inside another event which is updated every time something happens. But socket connection repeats the previous result with every new update.
I tried initializing socket within componentDidMount lifecyle and it simply does not work.
class UploadComponent extends Component {
constructor (props) {
super(props);
this.state = {
endpoint: "http://localhost:3000",
}
this.uploadModal = this.uploadModal.bind(this);
}
uploadModal () {
update.on('success', file => {
let {endpoint} = this.state;
let socket = socketIOClient(endpoint, {transports: ['websocket', 'polling', 'flashsocket']});
socket.on('data', (mydata) => {
console.log(mydata) // <-- This gets fired multiple times.
})
})
}
// some more code //
}
I want to trigger socket whenever "update" event is fired without message duplication.
As sockets are emitting multiple times on Angular with nodejs happened the same with me for sockets, i tried by removing the socket listeners by this.socket.removeListener( "Your On Event" );,
This helped me solved the issue of multiple socket calls, try it, it may help !
Unless you can guarantee success is called only once, then you'll need to initialize the socket connection / event handler outside this function
class UploadComponent extends Component {
constructor (props) {
super(props);
const endpoint = "http://localhost:3000";
this.state = { endpoint };
this.uploadModal = this.uploadModal.bind(this);
this.socket = socketIOClient(endpoint, {transports: ['websocket', 'polling', 'flashsocket']});
this.socket.on('data', (mydata) => {
console.log(mydata)
})
}
uploadModal() {
update.on('success', file => {
// this.socket.emit perhaps?
})
}
}
As James have suggested I have put my socket logic in the constructor. But it was only being fired after my component remounts.
After looking at my nodejs server code I tried to replace
// some code //
io.on('connection', (client) => {
client.emit('data', {
image: true,
buffer: imageBuffer.toString('base64'),
fileName: meta.name
})
})
with this
// some code //
io.emit('data', {
image: true,
buffer: imageBuffer.toString('base64'),
fileName: meta.name
})
and it works!
Also I had to close socket in componentWillUnmount to avoid multiple repeated data.

Flux and WebSockets

I'm using Flux and WebSocket in my Reactjs application and during implementation I've encountered some problems.
Questions:
Assuming I have a set of a set of actioncreators and a store for managing the WebSocket connection, and that the connection is started in a actioncreator (open(token)), where should I put my conn.emit's and how do I get other actions access to my connection object so that they can send data to the backend?
Do I have to pass it as an argument to the actions that are called in the views (eg. TodoActions.create(conn, todo)) or is there a smarter way?
Current code is here
I'm using ES6 classes.
If I have omitted anything necessary in the gist, please let me know.
EDIT:
This is what I have concocted so far based on glortho's answer:
import { WS_URL } from "./constants/ws";
import WSActions from "./actions/ws";
class WSClient {
constructor() {
this.conn = null;
}
open(token) {
this.conn = new WebSocket(WS_URL + "?access_token=" + token);
this.conn.onopen = WSActions.onOpen;
this.conn.onclose = WSActions.onClose;
this.conn.onerror = WSActions.onError;
this.conn.addEventListener("action", (payload) => {
WSActions.onAction(payload);
});
}
close() {
this.conn.close();
}
send(msg) {
return this.conn.send(msg);
}
}
export default new WSClient();
You should have a singleton module (not a store or an action creator) that handles opening the socket and directing traffic through. Then any action creator that needs to send/receive data via the socket just requires the module and makes use of its generic methods.
Here's a quick and dirty untested example (assuming you're using CommonJS):
SocketUtils.js:
var SocketActions = require('../actions/SocketActions.js');
var socket = new WebSocket(...);
// your stores will be listening for these dispatches
socket.onmessage = SocketActions.onMessage;
socket.onerror = SocketActions.onError;
module.exports = {
send: function(msg) {
return socket.send(msg);
}
};
MyActionCreator.js
var SocketUtils = require('../lib/SocketUtils.js');
var MyActionCreator = {
onSendStuff: function(msg) {
SocketUtils.send(msg);
// maybe dispatch something here, though the incoming data dispatch will come via SocketActions.onMessage
}
};
Of course, in reality you'll be doing better and different things, but this gives you a sense of how you might structure it.

Categories

Resources