I'm making a Socket.IO app, and trying to add a client-side listener for an event, in addition to a listener I already have. The problem is that the existing code is quite hard for me to make sense of, as I didn't write sections of it and am new to Socket.IO, so I don't know where to put my second event listener.
I've tried adding it in right before and after my first event listener, with no success.
The existing code, with one socket.on listener, besides 'connect':
$(function () {
var socket = io();
socket.on('connect', function(){
var id = socket.io.engine.id;
document.getElementById("os").innerHTML = id
});
$('form').submit(function(){
socket.emit('chat message', $('#m').val())
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
var form = $('#m').val();
//logic for commands
var help = /#help/;
var kill = /#kill/;
var admin = /SUDO/;
var private = /#to/;
var one = help.test(msg);
var two = kill.test(msg);
var three = admin.test(msg);
var four = private.test(msg);
if (one == true) {
$('#messages').append($('<li>').text('[SYSTEM]: The "#help" command has been activated. The following is an automated response and the user message which activated #help will appear below it in the chat stream. '));
$('#messages').append($('<li>').text("[#HELP]: This message is a brief overview of how to use Megaphone: type a message into the bar above, and hit enter to send it. Refresh the window to clear messages, and to leave, simply close the tab."));
function delay(ms, cb) { setTimeout(cb, ms) }
document.title = "New Message!";
audio.play();
delay(5000, function() {
document.title = "Megaphone";
})
} if (two == true && three == true) {
location = "https://google.com"
} if (two == true && three == false) {
$('#messages').append($('<li>').text(' [SYSTEM]: ATTEMPTED ACCESS TO AN ADMIN COMMAND DETECTED. THE COMMAND CANNOT BE USED WITHOUT AN ADMIN PASSPHRASE.'));
function delay(ms, cb) { setTimeout(cb, ms) }
document.title = "New Message!";
audio.play();
delay(5000, function() {
document.title = "Megaphone";
})
} if (three == true) {
var adminmsg = msg.split('SUDO')[1]
$('#messages').append($('<li>').text(' [ADMIN]: ' + adminmsg));
function delay(ms, cb) { setTimeout(cb, ms) }
document.title = "New Message!";
audio.play();
delay(3000, function() {
document.title = "Megaphone";
})
} if (four == true) {
var privatemessage = msg.split('#to')[0];
var recipientid = msg.split('#to')[1];
socket.emit('private message', { recipient: recipientid, message: privatemessage });
} else {
$('#messages').append($('<li>').text(' [USER]: ' + msg));
function delay(ms, cb) { setTimeout(cb, ms) }
document.title = "New Message!";
audio.play();
delay(5000, function() {
document.title = "Megaphone";
})
};
});
});
The event listener I'd like to add:
socket.on("dm", function(data) {
alert(data.description);
}
Server:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.get('/about', function(req, res){
res.sendFile(__dirname + '/about.html');
});
http.listen(3000, function(){
console.log('listening on *:3000. Megaphone is functional.');
});
io.on('connection', function(socket) {
console.info(`Client connected [id=${socket.id}]`);
socket.on('disconnect', function(){
console.info(`Client gone [id=${socket.id}]`);
});
});
io.on('connection', function(socket){
socket.on('private message', ({ recipient, message }) => {
io.to(recipient).emit("dm", {description: message});
console.info(message + ' ' + recipient)
})
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
When I insert the second event listener right before or after the first, it doesn't seem to work as there's no alert.
Related
To register a callback for a specific method in SignalR (JavaScript), you can do the following:
hubConnection.on("MyMethod", (...) => { ... });
However, is it possible to be able to listen to all methods and to get all arguments?
I don't believe so because you have to register all of your callbacks before starting the connection. This example from the docs shows this.
"use strict";
var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
//Disable send button until connection is established
document.getElementById("sendButton").disabled = true;
connection.on("ReceiveMessage", function (user, message) {
var msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
var encodedMsg = user + " says " + msg;
var li = document.createElement("li");
li.textContent = encodedMsg;
document.getElementById("messagesList").appendChild(li);
});
connection.start().then(function () {
document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
return console.error(err.toString());
});
document.getElementById("sendButton").addEventListener("click", function (event) {
var user = document.getElementById("userInput").value;
var message = document.getElementById("messageInput").value;
connection.invoke("SendMessage", user, message).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});
I'm using node.js to read data from socket on my web application (server). I receive data and make some changes on webpage (ex: change the color of polyline) but when a client after that changes connects, cannot see the changed color unless a new data is sent to server! So how client can see the previous changes which were on server?
here is my code
app.js
var http = require('http');
var express = require('express'),
app = module.exports.app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server); //pass a http.Server instance
server.listen(3000); //listen on port 80
app.use(express.static('public'));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
//var app = require('http').createServer(handler);
//var io = require('socket.io').listen(app);
var fs = require('fs');
var mySocket = 0;
//app.listen(3000); //Which port are we going to listen to?
function handler (req, res) {
fs.readFile(__dirname + '/index.html', //Load and display outputs to the index.html file
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
console.log('Webpage connected'); //Confirmation that the socket has connection to the webpage
mySocket = socket;
});
//UDP server on 41181
var dgram = require("dgram");
var server = dgram.createSocket("udp4");
server.on("message", function (msg, rinfo) {
console.log("Broadcasting Message: " + msg); //Display the message coming from the terminal to the command line for debugging
if (mySocket != 0) {
mySocket.emit('field', "" + msg);
mySocket.broadcast.emit('field', "" + msg); //Display the message from the terminal to the webpage
}
});
server.on("listening", function () {
var address = server.address(); //IPAddress of the server
console.log("UDP server listening to " + address.address + ":" + address.port);
});
server.bind(41181);
index.html
<html>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://192.168.1.14:3000');
socket.on('field', function (data) {
console.log(data);
$("#field").html(data);
switch(data)
{
case "1":
$("#path1").css("stroke", "red");
$("#progress1").css("backgroundColor", "red");
break;
}
});
</script>
<body>
<polyline id="path1" points="600,270 560,262 460,270 440,300" style="fill:none;stroke:green;stroke-width:3" />
</body>
</html>
On connection you have to emit already existing changes to socket client.
var myMessage;
io.sockets.on('connection', function (socket) {
console.log('Webpage connected'); //Confirmation that the socket has connection to the webpage
mySocket = socket;
mySocket.emit('field', "" + myMessage); // <<-- like this
server.on("message", function (msg, rinfo) {
console.log("Broadcasting Message: " + msg); //Display the message coming from the terminal to the command line for debugging
if (mySocket != 0) {
myMessage = msg;
mySocket.emit('field', "" + msg);
mySocket.broadcast.emit('field', "" + msg); //Display the message from the terminal to the webpage
}
});
});
I'm trying to emit messsage to specific rooms, once the "joinedRoom' listener is triggered by the client, the code works fine if I place my code outside the joinedRoom listeners, otherwise it does nothing.
Code:
app.get('/room/:room/user/:user', function(req, res){
var room = {
username: req.params.user,
roomname: req.params.room
};
res.render('room', room);
});
var users = {};
io.sockets.on('connection', function (socket) {
socket.on('joinedRoom', function(roomData){
socket.username = roomData.username;
socket.room = roomData.roomname;
console.log("Roomname: " + socket.room);
console.log("Username: " + socket.username);
socket.join(socket.room);
socket.broadcast.to(socket.room).emit('newUser', socket.username);
socket.on('disconnect', function(){
socket.broadcast.emit('userLeft', socket.username);
socket.leave(socket.room);
console.log('Connection id: ' + socket.id);
});
});
});
Client code:
var socket, roomname, ioRoom;
var socket = io.connect('http://localhost:3000');
socket.on('enterRoom', function(roomname){
console.log("ENTERED ROOM: " + roomname);
});
socket.on('newUser', function(username){
pushUserName(username);
pushUserStatus(username, ' has joined the room <br/>')
});
socket.on('newRoom', function(data){
alert(data)
});
socket.on('userLeft', function(username){
pushUserStatus(username, ' has left the room <br/>')
})
function pushUserName(username){
var el = document.getElementById("username");
el.innerHTML += username + '<br/>';
}
function pushUserStatus(username, message){
var el = document.getElementById("joined");
el.innerHTML += username + message;
}
Code the emits "joinedRoom" event:
doctype html
head
title Sala #{roomname}
script(src="https://cdn.socket.io/socket.io-1.4.5.js")
script(type="text/javascript").
var socket = io.connect('http://localhost:3000');
var roomData = {
roomname: '#{roomname}',
username: '#{username}'
}
socket.emit('joinedRoom', roomData);
script(src="../../../js/room.js")
body
p#joined
h1 Room's name: #{roomname}
h2 Your nickname: #{username}
h2 Players:
p#username.player-row
I saw the docs and some sample code and everything seems to be correct (when it comes simply to syntax) am I missing something simple here?
Thanks!
I think you need to register your disconnect event listener outside of your connection event listener.
Code:
app.get('/room/:room/user/:user', function(req, res){
var room = {
username: req.params.user,
roomname: req.params.room
};
res.render('room', room);
});
var users = {};
io.sockets.on('connection', function (socket) {
socket.on('joinedRoom', function(roomData){
socket.username = roomData.username;
socket.room = roomData.roomname;
console.log("Roomname: " + socket.room);
console.log("Username: " + socket.username);
socket.join(socket.room);
socket.broadcast.to(socket.room).emit('newUser', socket.username);
});
socket.on('disconnect', function(){
// need more logic here
});
});
For those who might have a similar problem the code is mostly correct but I was missing this:
Instead of:
socket.emit('joinedRoom', roomData);
Should be:
socket.on('connect', function(){
socket.emit('joinedRoom', roomData);
})
:)
Am still new to socket.io, Am trying to pass a value to the server side and store it in a global var which I can then use to do some logic with ARI.
So on my server side I have:
io.sockets.on('muting', function (data) {
mute = data;
console.log("client side:" + mute);
});
Entire server side code for clarity:
var ari = require('ari-client');
var util = require('util');
var chanArr = [];
var test;
var mute;
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
//ARI client
ari.connect('http://localhost:8088', 'asterisk', 'asterisk', clientLoaded);
function clientLoaded(err, client) {
if (err) {
throw err;
}
// find or create a holding bridges
var bridge = null;
client.bridges.list(function (err, bridges) {
if (err) {
throw err;
}
bridge = bridges.filter(function (candidate) {
return candidate.bridge_type === 'mixing';
})[0];
if (bridge) {
console.log(util.format('Using bridge %s', bridge.id));
} else {
client.bridges.create({
type : 'mixing'
}, function (err, newBridge) {
if (err) {
throw err;
}
bridge = newBridge;
console.log(util.format('Created bridge %s', bridge.id));
});
}
});
// handler for StasisStart event
function stasisStart(event, channel) {
console.log(util.format(
'Channel %s just entered our application, adding it to bridge %s',
channel.name,
bridge.id));
channel.answer(function (err) {
if (err) {
throw err;
}
bridge.addChannel({
channel : channel.id
}, function (err) {
var id = chanArr.push(channel.name)
console.log("Value: " + test);
test = channel.name;
updateSip);
if (err) {
throw err;
}
//If else statement to start music for first user entering channel, music will stop once more than 1 enters the channel.
if (chanArr.length <= 1) {
bridge.startMoh(function (err) {
if (err) {
throw err;
}
});
} else if (chanArr.length === 2) {
bridge.stopMoh(function (err) {
if (err) {
throw err;
}
});
} else {}
});
});
}
// handler for StasisEnd event
function stasisEnd(event, channel) {
console.log(util.format(
'Channel %s just left our application', channel.name));
console.log(channel.name);
var index = chanArr.indexOf(channel.name);
chanArr.splice(index, 1);
updateSip();
}
client.on('StasisStart', stasisStart);
client.on('StasisEnd', stasisEnd);
client.start('bridge-hold');
}
//Socket.io logic here
server.listen(3009, function () {
console.log('listening on *:3009');
});
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.sendfile(__dirname + "/testPage.html");
});
io.sockets.on('connection', function (data) {
updateSip();
});
io.sockets.on('muting', function (data) {
mute = data;
console.log("client side:" + mute);
});
function updateSip() {
console.log("Value: " + test);
io.sockets.emit('sip', chanArr);
}
And on my client side:
$(document).on('click', '#kick', function() {
mute = !mute;
socket.emit('muting', mute);
console.log(mute)
});
Full client side code:
jQuery(function ($) {
var socket = io.connect();
var mute = false;
var $sip = $('#sip');
socket.on('sip', function (data) {
var sip = '';
$(".exe").remove();
for (i = 0; i < data.length; i++) {
sip += data[i];
if (sip) {
$sip.append('<tr class="exe">\
<td>' + sip + '</td>\
<td><button class="btn btn-default mute" id="kick" type="submit">Mute</button></td>\
<td><button class="btn btn-default kick" id="kicks" data-toggle="modal" data-target="#myModal" type="submit">Kick</button></td>\
</tr>');
} else {
$sip.append('Currently no extensions');
}
sip = '';
}
});
$('.kick').click(function () {
$('#myInput').focus()
});
$(document).on('click', '#kick', function () {
mute = !mute;
socket.emit('muting', mute);
console.log(mute)
});
});
Am missing something very small, yet cant figure it out.
EDIT: I am not getting error messages, seems am not passing the information server side at all for some reason.
Am using express.
Kind regards.
From socket io doc: http://socket.io/docs/#using-with-the-express-framework
You could try to wrap you 'muting' event listener in the 'connection' event listener. Note that you will use the socket parameter from the 'connection' event to listen to 'muting'
server side:
io.sockets.on('connection',function (socket) {
updateSip();
socket.on('muting', function (data) {
mute = data;
console.log("client side:" + mute);
});
});
var socket = io.connect();
No you are not reaching your server !
//Socket.io logic here
server.listen(3009, function () {
console.log('listening on *:3009');
});
Your socket server seem to be listenning on port 3009, so you have to tell your client where is your server (the path -> ex : http://myoffice.localhost ) and the port to reach the server
try to update client side with :
io.connect("wss://" + document.location.hostname + ':' + 3009);
I'm building a simple messaging server and it works perfect using the socket.broadcast.emit() however if you use the socket.broadcast.in(room).emit() it dose not connect up. I've include the server code and client code below.
server
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var Parse = require('parse').Parse;
var room;
app.get('/', function(req, res){
res.sendfile('index.html');
});
// When a new connection is launched
io.on('connection', function(socket){
console.log('user connected: '+socket.id);
//========== INIT connection =========
// once a client has connected, we expect to get a ping from them saying what room
// they want to join
socket.on('room', function(data) {
room = data;
socket.join(room);
console.log(' + User: '+socket.id+' - joined Room: ['+room+']');
console.log(' + User: '+socket.id+' - has Rooms: ['+socket.rooms+']');
// Display all sockets connected to room
inRoom(room);
});
//======== Delegates messages ========
socket.on('message_send', function(data){
var JSONdata = JSON.parse(data);
var room_l = JSONdata.chat_id;
var msg = JSONdata.message;
console.log('Room: ' + room_l + ' - Message: ' + msg);
// Send message
//io.emit('message_received', msg);
//socket.broadcast.emit('message_received', msg);
io.in('TZRfM7V5HH').emit('message_recieved', msg);
//io.to(room_l).emit('message_received', msg);
// Save message to parse
parseSAVE(data);
});
});
Client
<script>
var socket = io();
var msg = $('#m').val();
var room = 'TZRfM7V5HH';
$( document ).ready(function() {
socket.emit('room',room);
socket.emit('message_send', '{"chat_id":"'+room+'","message":"yoyoyo shits to hype"}');
});
$('form').submit(function(){
$msg = $('#m').val();
socket.emit('message_send', '{"chat_id":"'+room+'","message":"'+$msg+'"}');
$('#messages').append($('<li>').text($msg));
$('#m').val('');
return false;
});
socket.on('message_received', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
I have been playing around with this all week and I cant seem to figure out whats wrong with my implementation, any help or pointers would be greatly appreciated!