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

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

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?

socket.emit and socket.on is not connected

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")

Node.js Socket.io - How to emit messages to specific rooms within a listener?

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;
}
I saw the docs and some sample code it everything seems to be correct (when it comes simply to syntax) am I missing something simple here?
Thanks!
EDIT (joinedRoom emitter):
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

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='';
});

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