socket.io client 's namespace invalid - socket.io

I am running on the latest version of socket.io, the server code and client code below works well.
// server
const { Server } = require("socket.io"),
http = require('http');
const httpserver = http.createServer();
io.on("connection", async (socket) => {
socket.on("error", (err) => {
console.log(err.message);
});
socket.on('disconnect', function () {
console.log('socket disconnect');
})
});
const io = new Server(httpserver, {
cors: { origin: "*", methods: ["GET", "POST"],}
});
httpserver.listen(3001, () => {
console.log('listening on *:3001');
});
// client
import { io, Socket } from "socket.io-client";
const socket = io('ws://127.0.0.1:3001', {
transports: ["websocket"]
});
socket.on("connect_error", (err) => {
console.log(`connect_error due to ${err.message}`);
});
then I tried to work with namespace in socket.io
// server
io.of("device").on("connection", async (socket) => {
socket.on("error", (err) => {
console.log(err.message);
});
socket.on('disconnect', function () {
console.log('socket disconnect');
})
});
// client
const socket = io('ws://127.0.0.1:3001/device', {
transports: ["websocket"]
});
running the code gives me an error saying
'connect_error due to Invalid namespace''
I can't figure out what goes wrong

Using ws://127.0.0.1:3001/device means you are trying to reach the namespace named '/advice', which does not exist on the server.
I think you are looking for the path option instead:
const socket = io("ws://127.0.0.1:3001", {
path: "/device",
transports: ["websocket"]
});
References:
https://socket.io/docs/v4/client-initialization/
https://socket.io/docs/v4/client-options/#path
https://socket.io/docs/v4/namespaces/

Related

socket.io not working once deployed on 000webhost

I read through other post with similar issue which I couldn't solve. I created a simple chat using socket.io, express. On the localhost its working but not on the 000webhost. I'm probably missing a code somewhere.
Tried adding line of codes on the server file and the client side but still couldn't get it to run.
server side
const express = require("express");
const Socket = require("socket.io");
const app = express();
const server = require("http").createServer(app);
const io = Socket(server, {
cors: {
origin: "*",
method: ["GET", "POST"]
}
})
let PORT = 5000;
server.listen(PORT, () => {
console.log("listening on port: ", PORT)
})
const users = [];
io.on("connection", (socket) => {
console.log("connected to", socket.id)
socket.on("adduser", (username)=>{
socket.user = username;
users.push(username);
io.sockets.emit("users", users)
})
socket.on("message", (message)=>{
io.sockets.emit("message_client", {
message,
user: socket.user
})
})
socket.on("disconnect", () => {
console.log("we are disconnecting...: ", socket.user)
if (socket.user){
users.splice(users.indexOf(socket.user), 1)
io.sockets.emit("users", users);
console.log('remaining users: ', users)
}
})
})

SocketIO 4 - won't emit to the room

I have following server code:
const path = require("path");
const http = require("http");
const express = require("express");
const {instrument} = require('#socket.io/admin-ui')
const {jwtDecode, jwtVerify, resignJwt} = require('jwt-js-decode')
const secret =
"xxxxxxx";
const app = express()
const server = http.createServer(app)
const io = require("socket.io")(server, {
cors: {
origin: ["https://admin.socket.io", "http://localhost:3001"],
credentials: true
},
});
let servantID = ''
io.use((socket, next) => {
const header = socket.handshake.headers["authorization"];
jwtVerify(header, secret).then((res) => {
if (res === true)
{
const jwt = jwtDecode(header);
servantID = jwt.payload.iss;
return next()
}
return next(new Error("authentication error"));
});
});
instrument(io, { auth: false });
server.listen(3000, () =>
console.log('connected')
)
io.on('connection', socket => {
socket.on("join", (room, cb) => {
console.log('Joined ' + room);
socket.join(room);
cb(`Joined the best room ${room}`)
});
socket.on('newOrder', function (data) {
socket.to('servant').emit('this', data);
console.log(data);
})
socket.on("thisNew", function (data) {
console.log('this new');
});
socket.on('disconnect', () => {
console.log('user disconnected');
});
})
And client side code:
socket.emit('join', 'servant', message => {
console.log(message)
})
socket.on('this', () => {
console.log('this event')
})
socket.emit('newOrder', 'data')
When I emit like this:
socket.to('servant').emit('this', data);
the client doesn't receive anything, but if I emit without room:
socket.emit('this', data);
the event and data are received on the client side.
What am I doing wrong here?

How to use the controller when working with sockets in AdonisJS

How to call the controller when I do emit in socket.io
I want that when calling emit from the client the data is first saved in the db and then sent to it.
My code:
import SocketIO from '#ioc:Socket.IO'
SocketIO.afterStart(() => {
const io = SocketIO.io()
io.use((socket, next) => {
//Middleware
next()
});
io.on('connection', (socket) => {
io.emit(`room.6`, {
type: 'connected'
//role: socket.handshake.query.user
});
socket.on('disconnect', () => {
io.emit(`room.6`, {
type: 'disconnected',
//role: socket.handshake.query.user
})
});
socket.on(`room.6`, (data) => {
io.emit(`room.6`, //Here the controller should be called)
});
});
})

Socket.io+AWS API gateway socket keeps on reconnecting and connect is never fired

AWS recently launched API gateway with sockets and it can proxy to lambda. In my observation AWS api socket is completely wss so I have done custom connect setting which is there in the code section. lambda and other setting I learned tested with wscat successfully as described in this link -
https://hackernoon.com/websockets-api-gateway-9d4aca493d39
But on integration with socket.io in browser it just keeps on reconnecting after 18-19 Seconds and connect is never fired! lambda and api gateway timeout is 30 Seconds which I think can be ignored as it doesn't interrupt the connection with wscat for 4-5 minutes.
I am new to sockets and the code in comments shows failed tries. Also tried googling but couldn't find much about AWS API socket and Socket.io. So any guidance or support is appreciated
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
</head>
<script>
socket = io(
`wss://abcd.execute-api.us-east-1.amazonaws.com/prod`
, {
path: `/prod/`,
forceNew: true,
// autoConnect: false,
// reconnection: false,
upgrade: true,
transports: ['websocket',
'polling',
'flashsocket'
]
});
socket.on('connect', function () {
socket.emit({"action":'message',"data":"hello return"}, () => {
console.log("message Sent");
});
});
// socket.emit({"action":'message',"data":"hello return"}, () => {
// console.log("message"); // true
// });
// socket.on('message', () => {
// console.log("message"); // true
// });
// socket.on("connection", function (socket) {
// console.log("connection")
// })
// socket.on('connect', () => {
// console.log("connect"); // true
// });
// socket.on('connected', () => {
// console.log("connected"); // true
// });
// socket.on('open', () => {
// console.log("open"); // true
// });
// socket.on('disconnect', (reason) => {
// console.log("disconnect->",reason);
// // if (reason === 'io server disconnect') {
// // // the disconnection was initiated by the server, you need to reconnect manually
// // socket.connect();
// // }
// // else the socket will automatically try to reconnect
// });
// socket.on('close', (reason) => {
// console.log("close->",reason);
// // if (reason === 'io server disconnect') {
// // // the disconnection was initiated by the server, you need to reconnect manually
// // socket.connect();
// // }
// // else the socket will automatically try to reconnect
// });
// // socket.open();
// // console.log(socket);
// socket.on( (res) => {
// console.log("res", res);
// });
// socket.on('reconnect', (attemptNumber) => {
// console.log("reconnected", attemptNumber); // true
// });
// socket.on('reconnecting', (attemptNumber) => {
// console.log("reconnecting...", attemptNumber); // true
// });
// socket.on('reconnect_error', (error) => {
// console.log("reconnect_error",error);
// });
// socket.on('reconnect_attempt', (error) => {
// console.log("reconnect_attempt->", error)
// // socket.io.opts.transports = ['polling', 'websocket'];
// });
// socket.on('error', (error) => {
// console.log("error->", error);
// });
// socket.on('ping', () => {
// console.log("ping");
// });
// socket.on('pong', () => {
// console.log("ping");
// });
</script>
</html>
I tested below Code in vue2 in Nuxt + Vuetify, I wanted to post for vue3 but I am still trying to get this done in little time I get after day Job. Any corrections are welcome. Thanks
export default {
data() {
return {
socketconnection: {},
listenersStarted: false,
}
},
created() {
this.onLoad()
this.notificationDialog()
this.startListeners()
this.$on('serverSelected', (server) => {
console.log('ran from $on server--', server)
const message = {
text: server,
right: false,
ts: new Date()
}
this.$store.commit('setMessage', message, { root: true })
})
},
methods: {
onLoad() {
try {
if (!localStorage.getItem('_t')) { return true }
if (this.socketconnection === true) {
console.log('socket already there... reconn unrequried!')
return true
}
const token = localStorage.getItem('_t')
const wsUri = `wss://test.example.com/prod?token=${token}`
const websocket = new WebSocket(wsUri)
websocket.onopen = (evt) => {
this.socketconnection = true
}
websocket.onclose = (evt) => { this.onClose(evt) }
websocket.onmessage = (evt) => { this.onMessage(evt) }
websocket.onerror = (evt) => { this.onError(evt) }
} catch (e) { console.log(e) }
},
onClose(evt) {
this.socketconnection = false
console.log('socket closed reconnecting...', evt)
this.onLoad()
},
onMessage(evt) {
console.log('evt---', evt)
this.$emit('serverSelected', evt.data)
},
onError(evt) {
console.log(evt)
},
}
}

HapiJS and Socket IO not emit

I'm trying to setup socket.io with hapi. I've setup a barebones repo here: https://github.com/imcodingideas/socketio-hapi-example but this is the gist of it. On the server.js I am listening for a connection
io.sockets.on('connection', (socket) => {
socket.emit({ msg: 'welcome' })
})
and on the client I'm sending a connection
socket.on('msg', data => {
console.log(data)
socket.emit('my other event', { my: 'data' })
})
I'm not getting any cors errors or nothing so it's able to connect.
Your code does work and it doesn't matter where you put the server.start().
The problem is your client side code. The event socket.on('connection') does not exist for the socket.io client. The event is called connect.
IO - Event: ‘connect’ Documentation
The following code snippet should work.
const socket = io('http://localhost:8081');
socket.on('connect', data => {
console.log('connected');
});
socket.on('msg', data => {
console.log(data);
});
setTimeout(() => {
socket.emit('another event', 'another events data')
}, 2000)
server:
const init = async () => {
const io = SocketIO.listen(server.listener)
io.sockets.on('connection', (socket) => {
socket.emit('msg', 'welcome')
socket.on('another event', (data) => {
console.log(data);
})
})
await server.start()
console.log(`Server running at: ${server.info.uri}`)
}
Do not start the server before you initialize the Socket Listener.
'use strict'
const Hapi = require('hapi')
const SocketIO = require('socket.io')
const server = Hapi.server({
port: 8081,
host: 'localhost'
})
const init = async () => {
// await server.start() // not here
const io = SocketIO.listen(server.listener)
io.sockets.on('connection', (socket) => {
socket.emit('msg', 'welcome')
})
await server.start() // but start it here.
console.log(`Server running at: ${server.info.uri}`)
}
init()
Pro tip
You can use Firecamp to test socket events and listeners visually

Resources