Socket.io call ack on connect event - javascript

Is there any way too utilize the ack argument on the connect event in Node.js? Something like this:
//client.js
socket.on('connect', (data) => {
console.log(data); // I want to print 'lol' here
});
//server.js
io.on('connect', (socket, ack) => {
ack('lol'); // TypeError: ack is not a function
});
Reference for ack: https://socket.io/docs/server-api/#socket-emit-eventname-args-ack

It doesn't look like the socket.connect() or socket.open() methods take an ack argument. I generally will emit a 'connected' event from the server once a connection from the client is established. You can receive this emission and add your behavior as needed.
server.js
io.on('connect', function(socket) {
socket.emit('connected');
});
client.js
socket.on('connected', function() {
console.log('Connected');
});

There is no specific ack data that you can send for the connect event. You can just .emit() a message to the client when the server receives the connect.
//client.js
socket.on('connect', () => {
console.log('client connected');
});
socket.on('welcome', function(data) {
console.log(data); // 'lol'
});
//server.js
io.on('connect', (socket) => {
// send welcome message upon connect
socket.emit('welcome', 'lol');
});

Related

How can i send data from a UDP server to a browser?

I try to make an application that receives from a third part application UDP packets.
I try to create a server UDP in NodeJS, but now when I receive the data I don't know how can I show it in a browser windows.
I explain better...my application receives data via udp in real time, the server processes them and should show them real time on a web page.
This is my code for UDP server in NodeJS:
const dgram = require('dgram');
const server = dgram.createSocket('udp4');
server.on('error', (err) => {
console.log(`server error:\n${err.stack}`);
server.close();
});
server.on('message', (msg, rinfo) => {
console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
console.log(` messaggio ricevuto ${msg}`);
});
server.on('listening', () => {
const address = server.address();
console.log(`server listening ${address.address}:${address.port}`);
});
server.bind({
adress:'127.0.0.1',
port:'41234'
});
// server listening address :41234
Thanks a lot for the reply
welcome to SO!
You could do something like below...
// Open a connection
var socket = new WebSocket('ws://localhost:41234/');
// When a connection is made
socket.onopen = function() {
console.log('Opened connection 🎉');
// send data to the server
var json = JSON.stringify({ message: 'Hello 👋' });
socket.send(json);
}
// When data is received
socket.onmessage = function(event) {
console.log(event.data);
}
// A connection could not be made
socket.onerror = function(event) {
console.log(event);
}
// A connection was closed
socket.onclose = function(code, reason) {
console.log(code, reason);
}
// Close the connection when the window is closed
window.addEventListener('beforeunload', function() {
socket.close();
});
This link should give you more info : https://www.sitepoint.com/real-time-apps-websockets-server-sent-events/ (above snippet is taken from this link)
You need a web server to send data to browser.
This link https://socket.io/get-started/chat will help you create a webserver.
You could send the message received on UDP port to the websocket as below
server.on('message', (msg, rinfo) => {
socket.emit('sendData', msg);
});

Client can receive events but can't emit

I have my client set up like this:
var socket = io();
socket.on('thing', function(socket){
console.log('A user connected: ' + socket.data);
});
function sendThing(){
var data = document.getElementById('myInput').value;
console.log(data)
socket.emit('message', { message: data });
}
I can receive events just fine, I have my server emit an event and it logs out fine:
io.on('connection', (socket) => {
io.emit('thing', { data: 'thisisathing' });
});
Edit: my on.message function:
io.on('message', (socket) => {
console.log(socket.message);
});
But my server never receives a message because the emit on the client side does not fire. Socket exists and I get no errors.
How do I fix this?
Try nesting your listener within your connection function like:
io.on('connection', (socket) => {
socket.on('message', (socket) => {
console.log(socket.message);
});
});
as described in the docs
I think you have to listen to message inside the connection :
io.on('connection', (socket) => {
socket.emit('thing', { data: 'thisisathing' });
socket.on('message', (data) => {
console.log(data.message);
});
});

What Express websocket events exist?

I am wondering what websocket events exist So far I have only been using the ws.on('message') event, but I would like to use an event that is triggered when the connection is established and closed. I tried adding ws.on('connection'), but that didn't get triggered.
My code:
app.ws('/', function (ws, req) {
ws.on('message', function (textChunk) {
//do stuff
}
});
});
Do I need some client side programming to do this?
I tried adding this, but it didn't trigger when I connected from my client.
ws.on('request', function () {
console.log("request");
});
The function provided to app.ws is the one executed when a new websocket is opened. So use it this way:
app.ws('/', function (ws, req) {
console.log("New connection has opened!");
ws.on('close', function() {
console.log('The connection was closed!');
});
ws.on('message', function (message) {
console.log('Message received: '+message);
});
});
After looking at the source code for express-ws it looks like you can do the following.
var express = require('express');
var app = express();
var expressWs = require('express-ws')(app);
// get the WebsocketServer instance with getWss()
// https://github.com/HenningM/express-ws/blob/5b5cf93bb378a0e6dbe6ab33313bb442b0c25868/index.js#L72-L74
expressWs.getWss().on('connection', function(ws) {
console.log('connection open');
});
// ... express middleware
// ... websocket middle ware
app.ws('/', function(ws, req) {
ws.on('message', function(msg) {
console.log(msg);
});
});
app.listen(3000);
Old Response
There are the following:
close
error
message
open
https://developer.mozilla.org/en-US/docs/Web/API/WebSocket#Attributes
Okay I found one more event that actually triggers. Now if only I would find one that gets called once on open connection.
app.ws('/', function (ws, req) {
ws.on('close', function() {
console.log('close connection');
});
ws.on('message', function (textChunk) {
//do stuff
}
});
});

socket.io error undefined is not a function

Installed websocket and socket.io on the server. When I load the browser page, I get this error in the console: Uncaught TypeError: undefined is not a function
(socket.io-1.2.1.js:1)
Here is the server side code:
// Require HTTP module (to start server) and Socket.IO
var http = require('http'), io = require('socket.io');
// Start the server at port 9602
var server = http.createServer(function(req, res){
// Send HTML headers and message
res.writeHead(200,{ 'Content-Type': 'text/html' });
res.end('<h1>Hello Socket Lover!</h1>');
});
server.listen(9602);
// Create a Socket.IO instance, passing it our server
var socket = io.listen(server);
// Add a connect listener
socket.on('connection', function(client){
// Success! Now listen to messages to be received
client.on('message',function(event){
console.log('Received message from client!',event);
});
client.on('disconnect',function(){
clearInterval(interval);
console.log('Server has disconnected');
});
});
And the client side code:
<script src="https://cdn.socket.io/socket.io-1.2.1.js"></script>
<script>
// Create SocketIO instance, connect
var socket = new io.Socket('localhost',{
port: 9602
});
socket.connect();
// Add a connect listener
socket.on('connect',function() {
console.log('Client has connected to the server!');
});
// Add a connect listener
socket.on('message',function(data) {
console.log('Received a message from the server!',data);
});
// Add a disconnect listener
socket.on('disconnect',function() {
console.log('The client has disconnected!');
});
// Sends a message to the server via sockets
function sendMessageToServer(message) {
socket.send(message);
}
</script>
Any help is appreciated.
k4elo
var socket = io("http://127.0.0.1:9000");
// Add a connect listener
socket.on('connect',function() {
console.log('Client has connected to the server!');
});
The above method works with the following cdn
You are creating server on HTTP not HTTPS
<script src='/socket.io/socket.io.js'></script>
instead of script src="https://cdn.socket.io/socket.io-1.2.1.js">

How to know when channel is subscribed/unsubscribed with socket.io

Just searched all the web to find how can I track inside node.js server when a channel is subscribed or unsubscribed. What I can do right know is the connect and disconnect bindings, but no clue how to do it with channels.
io.sockets.on('connection', function (socket) {
console.log("["+socket.id+"] Connected");
// handler to know when a socket subscribed a channel (*) ?
// handler to know when a socket unsubscribed a channel (*) ?
socket.on('disconnect', function () {
console.log("["+socket.id+"] Disconnect");
});
});
Is it possible?
You are looking for "socket.of('channelName')" ...
See Socket.io docs
SERVER:
var io = require('socket.io').listen(80);
var chat = io
.of('/chat')
.on('connection', function (socket) {
socket.emit('a message', {
that: 'only'
, '/chat': 'will get'
});
chat.emit('a message', {
everyone: 'in'
, '/chat': 'will get'
});
});
var news = io
.of('/news')
.on('connection', function (socket) {
socket.emit('item', { news: 'item' });
});
CLIENT:
<script>
var chat = io.connect('http://localhost/chat')
, news = io.connect('http://localhost/news');
chat.on('connect', function () {
chat.emit('hi!');
});
news.on('news', function () {
news.emit('woot');
});
</script>

Categories