Dynamic rooms with Socket.io and Node - node.js

I'm trying to use the new "room" feature in Socket.io v.7 to create dynamic chat rooms, but I'm having problems getting static rooms to work in my example. Based on the URL the user selects they should end up in room1 or room2. Anything the user enters in the chat should be broadcast to users in the same room. I have 2 browsers (chrome & ff) each with a tab open to /room1 and /room2, however nothing I type in seems to be broadcast to the other tabs. What am I doing wrong?
Server code
var app = require('express').createServer();
var io = require("socket.io").listen(app);
io.sockets.on('connection', function (socket) {
// join to room and save the room name
socket.on('join room', function (room) {
socket.set('room', room, function() { console.log('room ' + room + ' saved'); } );
socket.join(room);
})
socket.on('message', function(data) {
console.log("Client data: " + data);
// lookup room and broadcast to that room
socket.get('room', function(err, room) {
//room example - https://github.com/learnboost/socket.io
// neither method works for me
socket.broadcast.to(room).emit('new fan');
io.sockets.in(room).emit('new non-fan');
})
})
});
app.get('/room1', function(req, res){
res.render('example2-client.ejs', {layout:false});
});
app.get('/room2', function(req, res){
res.render('example2-client-2.ejs', {layout:false});
});
app.listen(4000);
Client code room 1
<!DOCTYPE HTML>
<html><head>
<title>Code review for Snipet</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="http://localhost:4000/socket.io/socket.io.js"></script>
<script>
$(document).ready(function() {
var socket = io.connect('http://localhost:4000');
$("#msgbox").keypress( function(event) {
if (event.which == '13') {
sendmsg();
event.preventDefault();
}
});
socket.on('connect', function (data) {
socket.emit('join room', 'room1' );
});
socket.on('message', function (data) {
add_message(data);
});
function add_message(m) {
$("#chatlog").append(m);
$("#chatlog").append("<BR>");
}
function sendmsg()
{
var r = $("#msgbox").val();
socket.emit('message', r );
add_message(r);
$("#msgbox").val('');
}
});
</script>
</head>
<body>
<div id="chat" style="height: 200px; width: 200px; border: 1px solid grey;">
<div id="chatlog" style="height: 178px; width: 200px; overflow-y: scroll;"></div>
<input type="text" id="msgbox" style="margin-left: 2px; width: 193px;">
</div>
</body>
</html>
Client code 2
<!DOCTYPE HTML>
<html><head>
<title>Code review for Snipet</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="http://localhost:4000/socket.io/socket.io.js"></script>
<script>
$(document).ready(function() {
var socket = io.connect('http://localhost:4000');
$("#msgbox").keypress( function(event) {
if (event.which == '13') {
sendmsg();
event.preventDefault();
}
});
socket.on('connect', function (data) {
socket.emit('join room', 'room2' );
});
socket.on('message', function (data) {
add_message(data);
});
function add_message(m) {
$("#chatlog").append(m);
$("#chatlog").append("<BR>");
}
function sendmsg()
{
var r = $("#msgbox").val();
socket.emit('message', r );
add_message(r);
$("#msgbox").val('');
}
});
</script>
</head>
<body>
<div id="chat" style="height: 200px; width: 200px; border: 1px solid grey;">
<div id="chatlog" style="height: 178px; width: 200px; overflow-y: scroll;"></div>
<input type="text" id="msgbox" style="margin-left: 2px; width: 193px;">
</div>
</body>
</html>

You don't seem to be listening to these events
socket.broadcast.to(room).emit('new fan');
io.sockets.in(room).emit('new non-fan');
on the client side you need:
socket.on('new fan', function (data) {
console.log('new fan');
});
You're also not sending the message to the clients.
Inside:
socket.on('message', function(data) { })
on the server, you need to do :
io.sockets.in(room).emit('message', data);

Related

How to show all clients including sender connected to a room in socket.io?

Below is the code for connecting a room named chat1. I'm able to show the connected clients except for sender by clicking on Chat Room 1 button in Active Users Window of index.html. I want to show sender's name also to be displayed in active users window along with other clients.
socket.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
usernames1 = [];
usernames2 = [];
usernames3 = [];
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
// var nsp = io.of('/chatroom');
// nsp.on('connection', function(socket) {
// console.log('ChatRoom namespace is created');
// // socket.on('hi',function(data){
// // console.log("Hi incoming")
// // })
// // nsp.emit('hi', 'Hello everyone!');
// });
io.of('/chatroom').on('connection', function(socket){ console.log("Connection establied")
socket.on('new user1',function(data, callback){
if(usernames1.indexOf(data)!=-1){
callback(false);
}
else
{
callback(true);
socket.username = data;
usernames1.push(socket.username);
socket.join('chat1',function(data)
{
console.log("In username "+usernames1)
console.log("\nIn socket.username "+socket.username+"\n")
updateUsernames();
});
}
// socket.join('chat1',function(data){
// console.log("Chat room 1 connected")
// });
})
function updateUsernames(){
console.log(usernames1);
socket.in('chat1').emit('comeon',usernames1)
}
});
http.listen(3000, function() {
console.log('listening on localhost:3000');
});
index.html
<!DOCTYPE html>
<html>
<head>
<title>Hello world</title>
</head>
<style>
#inp{
height:30px;
border:solid 1px #ccc;
}
.button1,.button2,.button3
{
background-color: #4CAF50;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
#mainWrapper{
display:none;
}
#chatWrapper{
float:left;
border:1px #ccc solid;
border-radius:10px;
background:#f4f4f4;
padding:10px;
}
#chatWindow{
height:300px;
}
#userWrapper{
float:left;
border:1px #ccc solid;
border-radius:10px;
background:#f4f4f4;
padding:10px;
margin-left:20px;
width:150px;
max-height:200px;
}
body{
background:#f9f9f9;
}
#form2,#form1,#form3{
display: inline-block;
margin-top:30px;
margin-left: 5%;
padding-left: 12px;
height: 140px;
width: 325px;
border:solid rgb(0, 0, 0)
}
error{
border:#101999
}
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js">
</script>
<script src = "/socket.io/socket.io.js"></script>
<script>
$(function () {
var socket = io('/chatroom');
var $form1= $('#form1');
var $form2= $('#form2');
var $form3= $('#form3');
var $username1=$('#username1');
var $username2=$('#username2');
var $username3=$('#username3')
var $users = $('#users');
var $error = $('#error');
$form1.submit(function(e){
e.preventDefault();
socket.emit('new user1', $username1.val(), function(data){
if(data){
// alert("Clicked")
$('.button1').hide();
$('.button2').hide();
$('.button3').hide();
$('#mainWrapper').show();
$form1.hide();
$form2.hide();
$form3.hide();
}
else
{
$('#error1 ').html("UserName is taken").effect("shake");
$('#error1 ').hide()
}
});
});
$form2.submit(function(e){
e.preventDefault();
socket.emit('new user2', $username.val(), function(data){
if(data){
// alert("Clicked")
$('.button1').hide();
$('.button2').hide();
$('.button3').hide();
$('#mainWrapper').show();
$form1.hide();
$form2.hide();
$form3.hide();
}
else
{
$('#error1').html("UserName is taken").effect("shake");
$('#error1').hide()
}
});
});
$form3.submit(function(e){
e.preventDefault();
$('.button1').hide();
$('.button2').hide();
$('.button3').hide();
$('#mainWrapper').show();
$form1.hide();
$form2.hide();
$form3.hide();
socket.emit('ch3');
});
socket.on('comeon', function(data){
alert("reached here")
var html = '';
for(i = 0; i < data.length; i++){
html += data[i] + '<br>';
}
console.log("Reached in usernames1")
console.log(data)
$users.html(html);
});
socket.on('comeon2', function(data){
alert("reached here")
var html = '';
for(i = 0; i < data.length; i++){
html += data[i] + '<br>';
}
console.log("Reached in usernames1")
$users.html(html);
});
})
</script> <div id="mainWrapper">
<h2>ChatIO</h2>
<body>
<div id="chatWrapper">
<div id="chatWindow"></div>
<form id="messageForm">
<input id="inp" type="text" size="35" id="message" placeholder="Say Something...">
<input id="inp" type="submit" value="Submit">
</form>
<button type="submit">Leave Room</button>
</div>
<div id="userWrapper"><strong>List of Active users</strong>
<div id="users"></div>
</div>
</div>
<div id="namesWrapper">
<div id="error1"></div>
<form id="form1">
Enter a username<input type="text" size="35" id="username1">
<input type="submit" class="button1" value="Chat Room 1">
</form></div><br>
<div id="namesWrapper">
<div id="error2"></div>
<form id="form2">
Enter a username<input type="text" size="35" id="username2">
<input type="submit" class="button2" value="Chat Room 2">
</form></div><br>
<div id="namesWrapper">
<div id="error3"></div>
<form id="form3">
Enter a username<input type="text" size="35" id="username3">
<input type="submit" class="button3" value="Chat Room 3">
</form></div>
</body>
</html>

Dynamic rooms in Socket.io

I'm new in node.js and socket.io. I didn't understand how to work with rooms. I'm creating something like a Private Messages. Each pair of users have their unique room.
From documentation:
io.on('connection', function(socket){
socket.join('some room');
});
But I need to create a room from client side. Because it's dynamic. How?
I met some examples https://gist.github.com/crtr0/2896891
server.js
io = socketio.listen(server);
io.sockets.on('connection', function(socket) {
socket.on('room', function(room) {
socket.join(room);
});
});
room = "abc123";
io.sockets.in(room).emit('message', 'what is going on, party people?');
This line drives me crazy. It seems to me stupid. Because server never know which room to use. Server just can handle multiple rooms.
room = "abc123";
Please, help or explain.
In you above code you have fixed room to abc123 , that you need to make it dynamic for all connected clients . You can provide room create option to user also you can provide logic to change/rename/leave/join room from client. Basically in your client and server you can apply below logical changes.
Client logic to update or change room :
socket.emit('switchRoom', newRoom);
socket.on('updaterooms', function(rooms, current_room) {
// Update new room logic
}
Server Logic to handle room change :
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);
});
Refer Below Example :
Socket.io Multi-room Example
Rooms and Namespace in socket.io
Okay, I solved my problem! If you use rooms within namespaces, don't forget write .of('your_namespace')
I created my own way of creating rooms from client side dynamically and it worked.
You can found video tutorial on youtube. https://www.youtube.com/watch?v=q5OKKudZTeY&list=PLZdwvOOinjFbzhZutEK9HvC56nicFXSpZ&index=8&t=0s
I used EJS for rendering.
Index.js
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
const path = require('path');
const roomsList = [];
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.get('/', (req, res) => {
//res.sendFile(__dirname + '/index.html');
res.render(path.join(__dirname,'/','index.html'),{rooms: roomsList});
});
app.get('/room/', (req, res) => {
var name = req.query.name;
res.render(path.join(__dirname,'/','rooms.html'),{rooms: name});
});
app.get('/addRoom/', (req, res) => {
var name = req.query.name;
roomsList.push(name);
console.log(JSON.stringify(roomList));
res.send(200);
});
const adminNameSpace = io.of('/admin');
adminNameSpace.on('connect', (socket) => {
//console.log('a user connected');
socket.on('join', (data)=>{
socket.join(data.room);
adminNameSpace.in(data.room).emit('chat message', `New Person joined the ${data.room} room `);
});
socket.on('disconnect', () => {
console.log('user disconnected');
});
socket.on('chat message', (data) => {
console.log('message: ' + data.msg);
adminNameSpace.in(data.room).emit('chat message', data.msg);
});
socket.on('send msg to all', (data) => {
console.log('message: ' + data.msg);
adminNameSpace.emit('chat message', data.msg);
});
});
server.listen(3000, () => {
console.log('listening on *:3000');
});
index.html
<html>
<head>
</head>
<body>
<p>Select your room!</p>
<p>Create Rooms</p>
<input id='input-room-name' />
<button onclick="createRoom()">Create Room</button><br/>
<script>
const rooms = '<%= rooms %>';
const roomList = rooms.split(',');
function createRoom()
{
var name = document.getElementById('input-room-name').value;
document.body.innerHTML+= `${name}<br /><br />`;
httpGet(name);
}
function httpGet(name)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", `/addRoom?name=${name}`,false);
xmlHttp.send(null);
return xmlHttp.responseText;
}
for (const name of roomList)
{
if(name!='')
document.body.innerHTML += `${name}<br /><br />`;
}
</script>
</body>
</html>
rooms.html
<!DOCTYPE html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
body { margin: 0; padding-bottom: 3rem; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
#form { background: rgba(0, 0, 0, 0.15); padding: 0.25rem; position: fixed; bottom: 0; left: 0; right: 0; display: flex; height: 3rem; box-sizing: border-box; backdrop-filter: blur(10px); }
#input { border: none; padding: 0 1rem; flex-grow: 1; border-radius: 2rem; margin: 0.25rem; }
#input:focus { outline: none; }
#form > button { background: #333; border: none; padding: 0 1rem; margin: 0.25rem; border-radius: 3px; outline: none; color: #fff; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages > li { padding: 0.5rem 1rem; }
#messages > li:nth-child(odd) { background: #efefef; }
</style>
</head>
<body>
<h1><%= rooms %></h1>
<button onclick="sendMSGToAll()">Send Message to all</button>
<ul id="messages"></ul>
<form id="form" action="">
<input id="input" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('/admin');
var form = document.getElementById('form');
var input = document.getElementById('input');
const room = '<%= rooms %>';
form.addEventListener('submit', function(e) {
e.preventDefault();
if (input.value) {
socket.emit('chat message', {msg: input.value, room});
input.value = '';
}
});
socket.on('chat message', function(msg) {
var item = document.createElement('li');
item.textContent = msg;
messages.appendChild(item);
window.scrollTo(0, document.body.scrollHeight);
});
socket.on('connect', () => {
socket.emit('join', {room: room});
})
function sendMSGToAll()
{
socket.emit('send msg to all', {msg: input.value, room});
}
</script>
</body>
</html>

Socket.io Can somebody help me why connected/disconnected message is appearing twice?

Below is my server side code where I want to display if user is connected or disconnected.But the user is connected and user is disconnected message is appearing twice. Can somebody help me why is it appearing twice?
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');
});
io.on('connect', function(socket) {
socket.broadcast.emit('chat message', 'a user connected!');
socket.on('disconnect', function() {
socket.broadcast.emit('chat message', 'user disconnected');
});
socket.on('chat message', function(msg) {
socket.broadcast.emit('chat message', msg);
});
});
http.listen(3000, function() {
console.log('listening on *:3000');
});
Client Code
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
<script>
var typing = false;
var timeout = undefined;
function timeoutFunction(){
typing = false;
socket.emit(noLongerTypingMessage);
}
function onKeyDownNotEnter(){
if(typing == false) {
typing = true
socket.emit(typingMessage);
timeout = setTimeout(timeoutFunction, 3000);
} else {
clearTimeout(timeout);
timeout = setTimeout(timeoutFunction, 3000);
}
}
</script>
</body>
</html>
You have two copies of this in your client file:
script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
Remove one of them.
Correct your order
io.on('connect', function(socket) {
socket.broadcast.emit('chat message', 'a user connected!');
socket.on('chat message', function(msg) {
socket.broadcast.emit('chat message', msg);
});
socket.on('disconnect', function() {
socket.broadcast.emit('chat message', 'user disconnected');
});
});

Socket IO can't emit

For a few days I've been trying to get the socket.io chat example to work from here. First I tried it by typing everything myself. But it didnt work. After that I tried it with the files from github.
the part
After I got the files from github I tried it did not work I have run
npm install
and it downloaded the dependencies into the node_modules folder, I also ran
npm install --save express#4.10.2
npm install --save socket.io
I got no errors on any of the commands.
I start the program with
node index.js
Which gives me the following message:
listening on *:30000
If I go to localhost:3000, I get the chat application as in the example. But no messages show up when posting the form.
However, when I use the following code to check connection:
io.on('connection', function(socket){
console.log('user connected');
});
it works, so the problem is in emitting data.
Also, the following code works:
server index.js
io.on('connection', function(socket){
var tweet = {user: "nodesource", text: "Hello, world!"};
// to make things interesting, have it send every second
var interval = setInterval(function () {
socket.emit("tweet", tweet);
console.log("tweeting");
}, 1000);
socket.on("disconnect", function () {
clearInterval(interval);
});
});
Client
socket.on("tweet", function(tweet) {
// todo: add the tweet as a DOM node
console.log("tweet from", tweet.username);
console.log("contents:", tweet.text);
});
So emitting and receiving from the server to the client works.
What I've tried
Run in different browsers
Run on different PC's
Copy from github
Type everything myself
Check the console in Chrome for errors (no errors found)
Change ports
Different paths (used c:\chat , d:\chat, c:\personalfiles\chat )
Disable firewall
What works
When following the tutorial, the part where a user connects and gets logged on the console work.
I get the chat page
Console says its listening
No errors
Any tips on how to solve this, or how to find what's wrong?
My index.html
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
$('form').submit(function(){
console.log('Send message');
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
</body>
</html>
My index.js
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');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
try this (for version <= 0.8):
io.configure(function () {
io.set("transports", ["xhr-polling"]);
io.set("polling duration", 10);
});
for version 1.0.x it would be something like:
var io = require('socket.io').listen(http, {
"transports": ['websocket',
'flashsocket',
'htmlfile',
'xhr-polling',
'jsonp-polling',
'polling'],
"polling duration": 10
});
Yours:
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
Are you sure it's not supposed to be this instead?
io.sockets.on('connection', function (socket) {
socket.on('chat message', function(msg){
io.sockets.emit('chat message', msg);
});
});

How to connect to Socket.IO from client to server

Im developing a real-time chat web-application for my site. My server acts a little different to the way i need to act. i have an Apache PHP server which node.js is not compatible on. My node server is public but to connect, i have to name a directory of the client from the server which means that when i open up the SERVER IP, it will display the client. I want to upload the client on another Hosting server and connect to my Socket.IO and node server from there. Here is my code.
Client
<!DOCTYPE html>
<html lang='en'>
<head>
<title>Chat</title>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js'></script>
<script src='node_modules/socket.io/socket.io.js'></script>
<script>
var socket = new io.Socket("127.0.0.1", {port:911});
socket.connect();
//Once connected
socket.on('welcome', function(data) {
$('#log ul').append('<li>' + data.salutation + '</li>');
});
//Displayig the data from the server
socket.on('data from server', function(data) {
$('#log ul').append('<li>' + data.message + '</li>');
});
$(function() {
var entry_el = $('#entry');
$('#entry').keypress(function(event) {
//13 on your keyboard is the key enter
if(event.keyCode == 13) {
var msg = entry_el.attr('value');
if(msg) {
socket.emit('data from client', {'text': msg});
entry_el.attr('value', '');
window.scrollBy(0, 1000000000000);
entry_el.focus();
}
}
});
});
/*SCRIPT DONE
CSS START
*/
</script>
<style type='text/css'>
body {
color: fff;
font-size: 14px;
margin: 0;
padding: 0;
font-family: Helvetica, Arial, Sans-Serif;
}
#log {
margin-bottom: 100px;
width: 100%;
}
#log ul {
padding: 0;
margin: 0;
}
#log ul li {
list-style-type: none;
}
#console {
position: fixed;
width: 100%;
font-size: 18px;
}
</style>
</head>
<body>
<h1>Chat</h1>
<div id='log'><ul></ul></div>
<div id='console'>
<input type='text' id='entry'/>
</div>
</body>
</html>
Server
var http = require('http').createServer(handler);
var io = require('socket.io').listen(http);
var sys = require('sys');
var fs = require('fs');
var clients = [];
http.listen(911);
function handler(request, response) {
//If the response is Positive (200)
response.writeHead(200, {
'Content-Type':'text/html'
});
sys.pump(rs, response);
};
//connecting to sockets
io.sockets.on('connection', function(socket) {
var username;
clients.push(socket);
socket.emit('welcome', {'salutation':'Welcome to this chat server!'});
socket.emit('welcome', {'salutation':'Please input your username:'});
socket.on('data from client', function(data) {
console.log('message: ' + data.text);
if(!username) {
username = data.text;
socket.emit('data from server', {'message': 'Welcome, ' + username + '!'});
return;
}
//the response when someone types something
var feedback = username + ' said: ' + data.text;
clients.forEach(function(socket) {
socket.emit('data from server', {'message': feedback});
});
});
});

Resources