socket.emit and socket.on is not connected - javascript

I was adding a chat page in my existing express app using socket.io.
My server code :
var io = socket(server);
io.on('connection', (socket) => {
console.log('made socket connection', socket.id);
// Handle chat event
socket.on('chat', function(data){
console.log("second");
io.sockets.emit('chat', data);
});
});
and my client code :
var socket = io.connect("http://localhost:3000/chat")
//Query elements
var message = document.getElementById('message'),
btn = document.getElementById('send'),
output = document.getElementById('output');
btn.addEventListener("click", function(){
socket.emit('chat', {
message: message.value,
});
console.log("First")
message.value = "";
})
socket.on('chat', function(data){
console.log("final function")
output.innerHTML += `<p>${data.message}</p>`;
});
socket.emit is fired on click in client side but socket.on in server doesn,t run.
Note : console.log('made socket connection', socket.id); run normally

there is an issue in your client side . you are trying to connecting with namsespaces "chat" , remove chat
var socket = io.connect("http://localhost:3000")

Related

Emit to a specific room using SocketIo

I'm trying to allow users on client-side pages to chat with other users on the same page (a room), but not with users on different pages. Right now my socket is emitting across all pages. I'd like to confine the emissions to one room for each page.
App.js server side code
const io = require('socket.io')(server, { cors: { origin: "*"}});
io.on('connection', (socket) => {
socket.on('chat message', (msg) => {
io.emit('chat message', msg);
});
});
Client side tag
<script src="/javascripts/socketIo.js"></script>
SocketIo.js
const socket = io();
const messages = document.getElementById('messages');
const form = document.getElementById('form');
const input = document.getElementById('input');
socket.on('connection', (socket) => {
socket.join(room);
});
form.addEventListener('submit', function (e) {
e.preventDefault();
if (input.value) {
const alias = socket.id.slice(-5);
socket.emit('chat message', alias + ": " + input.value);
input.value = '';
}
});
socket.on('chat message', function (msg) {
const item = document.createElement('ul');
item.textContent = msg;
messages.appendChild(item);
window.scrollTo(0, document.body.scrollHeight);
});
The current code sends messages to all users (no rooms). If I update the code below to include prefix "socket.to" like the docs instruct, messages stop sending altogether.
from
socket.emit('chat message', alias + ": " + input.value)
to
socket.to(room).emit('chat message', alias + ": " + input.value)
How do I get socket to send the messages to page-specific rooms?

Not showing client welcome message in socket.io / node.js

i made a primitive chatroom in nodejs and socket.io here and i am trying to get it to display the username and a welcome message to just the user as well as a message that shows all the other users that he/she joined here is my code
server code
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var usernames = {};
app.get('/', function(req, res){
res.sendfile('index.html');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
io.on('connection', function (socket) {
socket.on('adduser', function(username){
socket.username = username;
socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected to this room' + '<hr>');
socket.emit('welcomeuser', 'SERVER Welcome', username + '<hr>');
});
console.log('a user connected');
socket.on('disconnect', function () {
console.log('user disconected');
});
socket.on('chat-message', function (message) {
console.log('message : ' + message.text);
//excludes "socket" from getting the emit
socket.broadcast.emit("chat-message",message);
});
});
and here is my client code
var username = "";
var socket = io();
socket.on('connect', function(){
socket.emit('adduser', prompt("What's your name?"));
});
socket.on('updatechat', function (username, data) {
$('#chatlog-display-div').append('<b>'+username + ':</b> ' + data + '<br>');
});
socket.on('welcomeuser', function(username, data){
jQuery("#chatlog-display-div").append( username +'<hr>');
});
$('form').submit(function(e) {
e.preventDefault();
//gets the value from the message text feild and sets it as the message var
var message = {
text : $('#chat-box-div-txtinpt').val()
}
if (message.text.trim().length !== 0) {
socket.emit('chat-message',message);
//append the message to the chatlog-display-div
$('#chat-box-div-txtinpt').focus().val('');
jQuery("#chatlog-display-div").append('<div>'+message.text+'</div><hr>');
}
});
//clear the value of the txtinput after you focus it.
socket.on('chat-message', function (message) {
jQuery("#chatlog-display-div").append('<div>'+message.text+'</div><hr>');
});
can someone please help me

printing a variable into a div

I am atempting to build a chatroom with NodeJS and Socket.io and I have gotten so far as to get the users input and send it to the Node server but that's all I want to be able to display it up in a div
Client-side script
var socket = io();
$('form').submit(function(e) {
e.preventDefault();
// gets the value from the message text feild and sets it as the message var
var message = {
text: $('#chat-box-div-txtinpt').val()
}
if (message.text.trim().length !== 0) {
socket.emit('chat-message', message);
}
$('#chat-box-div-txtinpt').focus();
document.getElementById('chat-box-div-txtinpt').value='';
});
Server-side script
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res) {
res.sendfile('index.html');
});
http.listen(3000, function() {
console.log('listening on *:3000');
});
io.on('connection', function (socket) {
console.log('a user connected');
socket.on('disconnect', function () {
console.log('user disconected');
});
socket.on('chat-message', function (message) {
console.log('message: ' + message.text);
});
});
Here is the site
It appears you're using jQuery, so for this line: document.getElementById('chat-box-div-txtinpt').value=''; you could just do $('#chat-box-div-txtinpt').val('');
to answer your question: you could just do $('#chatlog-display-div').append(message.text)
Your code would end up looking something like this
$('form').submit(function(e) {
e.preventDefault();
//gets the value from the message text feild and sets it as the message var
var message = {
text : $('#chat-box-div-txtinpt').val()
}
if (message.text.trim().length !== 0) {
socket.emit('chat-message', message);
//append the message to the chatlog-display-div
$('#chatlog-display-div').append(message.text);
}
//clear the value of the txtinput after you focus it.
$('#chat-box-div-txtinpt').focus().val('');
});
please mark as accepted answer if you feel this adequately solves the issue.
To send messages to everyone from the server use emit() from io
on server
socket.on('chat-message', function (message) {
console.log('message : ' + message.text);
io.emit("chat-message",message);
});
on client
socket.on('chat-message',function(message){
//add message to the chat window
});
If you do not want the person sending the message to get the chat-message emit then use broadcast.emit() from the socket that sent it
//server
socket.on('chat-message', function (message) {
console.log('message : ' + message.text);
//excludes "socket" from getting the emit
socket.broadcast.emit("chat-message",message);
});
To actually put the message in the div just use any of jQuery's various methods html()/text()/append()
//client
socket.on('chat-message', function (message) {
jQuery(".chat-window").append('<div>'+message.text+'</div>');
});
You could simple .append the text to "chatlog-display-div" with a templet if you use ES6 could be something like
$('form').submit(function(e) {
e.preventDefault();
//gets the value from the message text feild and sets it as the message var
var message = {
text : $('#chat-box-div-txtinpt').val()
}
if (message.text.trim().length !== 0) {
socket.emit('chat-message', message);
document.getElementById('chatlog-display-div').append('<divclass="message-style" > ${message.text}</div>')
}
$('#chat-box-div-txtinpt').focus();
document.getElementById('chat-box-div-txtinpt').value='';
});

Emit() to everyone in /namespace - NodeJS, Socket.IO

I have tried several variations of trying to emit to all users connected to a particular /namespace, but have had no luck. I could be misunderstanding how sockets work.
But what I have right now is two browsers open on different pages. When a user connects to pageA, that user is now part of '/users' namespace. When a user connects to pageB, that user is now part of '/valets' namespace.
I have a .emit() on pageA that sends to server.js. I listen for it with .on(), and then try to run .emit() but to only the users in '/valets' namespace.
I am able to see in my terminal "listening for request valet" and the console.log(data) part.
I believe my problem is the usr_nsp.of('/valets').emit("incoming-request",{data:data}); portion. The other commented lines are what I have tried so far. They all give me an error: is not a function.
server.js
var app = require('http').createServer();
var io = require('socket.io')(app);
app.listen(3000, function(){
console.log('listening on port 3000');
});
var redis = require('socket.io/node_modules/redis');
// create custom namespace for Users
var room_number;
var usr_nsp = io.of('/users');
usr_nsp.on('connection', function(socket){
console.log('user has connected to /users namespace');
socket.on('request-valet', function(data){
console.log("listening for request valet");
console.log(data);
room_number = data.room_number;
socket.join(room_number);
// usr_nsp.broadcast.of('/valets').emit("incoming-request",{repark:data});
// usr_nsp.of('/valets').broadcast.emit("incoming-request",{repark:data});
// io.of('/valets').emit("incoming-request",{repark:data});
// socket.of('/valets').emit("incoming-request",{repark:data});
usr_nsp.of('/valets').emit("incoming-request",{repark:data});
});
});
var valet_nsp = io.of('/valets');
valet_nsp.on('connection', function(socket){
console.log('valet has connected to /valets namespace');
// var room_number;
socket.on('join-room', function(data){
// assign valet to room
room_number = data.room_number;
socket.join(room_number);
//valet_nsp.sockets.in(room_number).emit("request-accepted",{current_pos:current_pos})
});
socket.on('set-valet-starting-position', function(data){
//var valet_starting_pos = data.starting_position;
valet_nsp.sockets.in(room_number).emit('activate-directions-service', {repark:data});
})
socket.on('get-new-location', function(data){
// send the updated location only to User
// maybe use .broadcast??
valet_nsp.sockets.in(room_number).emit("update-valet-location", {current_pos:data});
});
});
pageB.html (sockets portion)
socket.on('incoming-request', function(data){
console.log("incoming request");
alert("incoming request");
// use data to display on html screen
});
The namespace handle you created is used to emit to users in that particular namespace. This should thus work:
var users = io.of('/users'),
valets = io.of('/valets');
users.on('connection', function(socket) {
socket.on('request-valet', function(data) {
valets.emit('incoming-request', { repark : data });
});
});

Js node - socket.io chat modificaion

Here is a simple chat example. How can I modify the script so that:
in the first 5s, the first user can send a message, and in the next 5s, the user can't send a message
in the next 5s (when the first user cannot send a message), the second user can send message and the first user gets a div (apIdv1) to display
index.html:
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
// on connection to server, ask for user's name with an anonymous callback
socket.on('connect', function(){
// call the server-side function 'adduser' and send one parameter (value of prompt)
socket.emit('adduser', prompt("What's your name?"));
});
// listener, whenever the server emits 'updatechat', this updates the chat body
socket.on('updatechat', function (username, data) {
$('#conversation').append('<b>'+username + ':</b> ' + data + '<br>');
});
// listener, whenever the server emits 'updaterooms', this updates the room the client is in
socket.on('updaterooms', function(rooms, current_room) {
$('#rooms').empty();
$.each(rooms, function(key, value) {
if(value == current_room){
$('#rooms').append('<div>' + value + '</div>');
}
else {
$('#rooms').append('<div>' + value + '</div>');
}
});
});
function switchRoom(room){
socket.emit('switchRoom', room);
}
// on load of page
$(function(){
// when the client clicks SEND
$('#datasend').click( function() {
var message = $('#data').val();
$('#data').val('');
// tell server to execute 'sendchat' and send along one parameter
socket.emit('sendchat', message);
});
// when the client hits ENTER on their keyboard
$('#data').keypress(function(e) {
if(e.which == 13) {
$(this).blur();
$('#datasend').focus().click();
}
});
});
</script>
<style type="text/css">
#apDiv1 {
position:absolute;
width:200px;
height:115px;
z-index:1;
left: 150px;
top: 20px;
background-color: #FF9900;
display:none;
}
</style>
<div style="float:left;width:100px;border-right:1px solid black;height:300px;padding:10px;overflow:scroll-y;">
<b>ROOMS</b>
<div id="rooms"></div>
</div>
<div style="float:left;width:300px;height:250px;overflow:scroll-y;padding:10px;">
<div id="conversation"></div>
<input id="data" style="width:200px;" />
<input type="button" id="datasend" value="send" />
</div>
<div id="apDiv1"></div>
app.js
var app = require('express').createServer()
var io = require('socket.io').listen(app);
app.listen(8080);
// routing
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
// usernames which are currently connected to the chat
var usernames = {};
// rooms which are currently available in chat
var rooms = ['room1','room2','room3'];
io.sockets.on('connection', function (socket) {
// when the client emits 'adduser', this listens and executes
socket.on('adduser', function(username){
// store the username in the socket session for this client
socket.username = username;
// store the room name in the socket session for this client
socket.room = 'room1';
// add the client's username to the global list
usernames[username] = username;
// send client to room 1
socket.join('room1');
// echo to client they've connected
socket.emit('updatechat', 'SERVER', 'you have connected to room1');
// echo to room 1 that a person has connected to their room
socket.broadcast.to('room1').emit('updatechat', 'SERVER', username + ' has connected to this room');
socket.emit('updaterooms', rooms, 'room1');
});
// when the client emits 'sendchat', this listens and executes
socket.on('sendchat', function (data) {
// we tell the client to execute 'updatechat' with 2 parameters
io.sockets.in(socket.room).emit('updatechat', socket.username, data);
});
socket.on('switchRoom', function(newroom){
// leave the current room (stored in session)
socket.leave(socket.room);
// join new room, received as function parameter
socket.join(newroom);
socket.emit('updatechat', 'SERVER', 'you have connected to '+ newroom);
// sent message to OLD room
socket.broadcast.to(socket.room).emit('updatechat', 'SERVER', socket.username+' has left this room');
// update socket session room title
socket.room = newroom;
socket.broadcast.to(newroom).emit('updatechat', 'SERVER', socket.username+' has joined this room');
socket.emit('updaterooms', rooms, newroom);
});
// when the user disconnects.. perform this
socket.on('disconnect', function(){
// remove the username from global usernames list
delete usernames[socket.username];
// update list of users in chat, client-side
io.sockets.emit('updateusers', usernames);
// echo globally that this client has left
socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
socket.leave(socket.room);
});
});
How can I show apDiv1 for the first 5s to one user, then make it disappear, and vice versa for the second user?
UPDATE with answer:
Why this now dont work?
app.js
var app = require('express').createServer()
var io = require('socket.io').listen(app);
app.listen(8080);
// routing
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
// usernames which are currently connected to the chat
var usernames = {};
// rooms which are currently available in chat
var rooms = ['room1','room2','room3'];
io.sockets.on('connection', function (socket) {
// when the client emits 'adduser', this listens and executes
socket.on('adduser', function(username){
// store the username in the socket session for this client
socket.username = username;
// store the room name in the socket session for this client
socket.room = 'room1';
// add the client's username to the global list
usernames[username] = username;
// send client to room 1
socket.join('room1');
// echo to client they've connected
socket.emit('updatechat', 'SERVER', 'you have connected to room1');
// echo to room 1 that a person has connected to their room
socket.broadcast.to('room1').emit('updatechat', 'SERVER', username + ' has connected to this room');
socket.emit('updaterooms', rooms, 'room1');
});
// when the client emits 'sendchat', this listens and executes
socket.on('sendchat', function (data) {
// we tell the client to execute 'updatechat' with 2 parameters
io.sockets.in(socket.room).emit('updatechat', socket.username, data);
});
socket.on('switchRoom', function(newroom){
// leave the current room (stored in session)
socket.leave(socket.room);
// join new room, received as function parameter
socket.join(newroom);
socket.emit('updatechat', 'SERVER', 'you have connected to '+ newroom);
// sent message to OLD room
socket.broadcast.to(socket.room).emit('updatechat', 'SERVER', socket.username+' has left this room');
// update socket session room title
socket.room = newroom;
socket.broadcast.to(newroom).emit('updatechat', 'SERVER', socket.username+' has joined this room');
socket.emit('updaterooms', rooms, newroom);
});
function redLightGreenLight() {
socket1.emit('redLight');
socket2.emit('greenLight');
}
setTimer('redLightGreenLight()', 5000);
// when the user disconnects.. perform this
socket.on('disconnect', function(){
// remove the username from global usernames list
delete usernames[socket.username];
// update list of users in chat, client-side
io.sockets.emit('updateusers', usernames);
// echo globally that this client has left
socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
socket.leave(socket.room);
});
});
index.html
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
// on connection to server, ask for user's name with an anonymous callback
socket.on('connect', function(){
// call the server-side function 'adduser' and send one parameter (value of prompt)
socket.emit('adduser', prompt("What's your name?"));
});
// listener, whenever the server emits 'updatechat', this updates the chat body
socket.on('updatechat', function (username, data) {
$('#conversation').append('<b>'+username + ':</b> ' + data + '<br>');
});
// listener, whenever the server emits 'updaterooms', this updates the room the client is in
socket.on('updaterooms', function(rooms, current_room) {
$('#rooms').empty();
$.each(rooms, function(key, value) {
if(value == current_room){
$('#rooms').append('<div>' + value + '</div>');
}
else {
$('#rooms').append('<div>' + value + '</div>');
}
});
});
function switchRoom(room){
socket.emit('switchRoom', room);
}
*socket.on('greenLight', function (data) {
// change div to enable sending a message
});
socket.on('redLight', function (data) {
// change div to index.html*
});
// on load of page
$(function(){
// when the client clicks SEND
$('#datasend').click( function() {
var message = $('#data').val();
$('#data').val('');
// tell server to execute 'sendchat' and send along one parameter
socket.emit('sendchat', message);
});
// when the client hits ENTER on their keyboard
$('#data').keypress(function(e) {
if(e.which == 13) {
$(this).blur();
$('#datasend').focus().click();
}
});
});
</script>
<style type="text/css">
#greenLight {
position:absolute;
width:200px;
height:115px;
z-index:1;
left: 150px;
top: 20px;
background-color: #FF9900;
display:none;
}
</style>
<div style="float:left;width:100px;border-right:1px solid black;height:300px;padding:10px;overflow:scroll-y;">
<b>ROOMS</b>
<div id="rooms"></div>
</div>
<div style="float:left;width:300px;height:250px;overflow:scroll-y;padding:10px;">
<div id="conversation"></div>
<input id="data" style="width:200px;" />
<input type="button" id="datasend" value="send" />
</div>
***<div id="greenLight"></div>***
Quoth beginerplus, "maybe is better to server to do job... how to change my script to do that? please write as example on an answer":
On the server:
function redLightGreenLight() {
socket1.emit('redLight');
socket2.emit('greenLight');
}
setTimer('redLightGreenLight()', 5000);
On the client:
socket.on('greenLight', function (data) {
// change div to enable sending a message
});
socket.on('redLight', function (data) {
// change div to index.html
});
There are two ways:
the server sends a message to each client after 5 seconds, using setTimer (or setInterval in case you need to repeat): client #1 can't send a message any more, and client #2 can. Then each client handles the message by changing the div content.
each client uses setTimer or setInterval on its own; this may have some advantages depending on your use case, but probably has the disadvantage that the timers won't start at exactly the same time.

Categories