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

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>

Related

Display incoming messages in different html page

This is piece of code for small chat.
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){
console.log('message: ' + msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
and html page:
<!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>
<script src="/socket.io/socket.io.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
});
</script>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
</html>
on console window I see received messages from client but what i want to achieve is when i open http://localhost:3000/msgmonitor i would like to see all this messages that are comming from clients. How to do this?

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

Node.js with socket.io, capturing form data to display on page

What I am trying to do is basic, but cant get my data back to the page. I want to capture some usewr information in a form before I direct them to a chat screen, once directed to the chat screen I will use form data to append their name and question(from the form) to the chat window.
I have edited the original post, if I change the line return data in index.js to:*
io.emit('user capture', data)
*...and comment out the display none on the chat window.
I get the data posted to the chat window, now I just need to be able to hide the chat window... Any ideas?
Below is 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[name="chat"] { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form[name="chat"] input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form[name="chat"] 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; }
/*.chat { display: none; }*/
</style>
</head>
<body>
<div class="pages">
<div class="user_capture">
<form name="user_capture" enctype='application/json'>
<button>Close</button><br/><br/>
<label for="username">Your Name: *</label><br/>
<input id="username" type="text" value="" name="username" autocomplete="off" required="required" /><br/>
<label for="email">Email: *</label><br/>
<input id="email" value="" name="email_address" autocomplete="off" /><br/>
<label for="phone">Phone:</label><br/>
<input id="phone" value="" name="phone" autocomplete="off" /><br/>
<label for="question">Question: </label><br/>
<textarea id="question" name="question">
</textarea required="required"><br/><br/>
<button>Chat</button>
</form>
</div>
<div class="chat">
<ul id="messages"></ul>
<form name="chat">
<input id="message" autocomplete="off" /><button>Send</button>
</form>
</div>
</div>
<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>
var socket = io();
$('form[name="user_capture"]').submit(function(){
var data = {
username:$('[name="username"]').val(),
question:$('[name="question"]').val()
}
socket.emit('user capture', data);
//return false;
});
socket.on('user capture', function(data){
$('form[name="user_capture"]').hide();
$('form[name="chat"]').show();
// $('#messages').append(data.username +' says: '+ data.question);
});
$('form[name="chat"]').submit(function(){
socket.emit('chat message', $('#message').val());
$('#message').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
</body>
</html>
Below is my index.js:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var status = 'Disconnected';
app.get('', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
var status = 'Connected';
socket.on('chat message', function(msg){
io.emit('chat message', msg);
io.emit('status', status);
});
socket.on('user capture', function(data){
io.emit('user capture', data);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
use following code
$('form[name="user_capture"]').click(function(e){
e.preventDefault();
var data = {
username:$('[name="username"]').val(),
question:$('[name="question"]').val()
}
So you guys were right the form was submitting refreshing the page and causing loss of data I also decided to not use a form at all.. Just inputs and tags as I am not using PHP so no need for POST. Below is my working code:
index.html
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { box-sizing: border-box; }
body { margin: 0; padding: 0; font: 13px Helvetica, Arial; }
[data-close] { float: right; }
[data-status] { width: 100%; }
.chat { display: none; }
.chat .send-area { background: #000; padding: 15px; position: fixed; bottom: 0; width: 100%; }
.chat .send-arae input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
.chat [data-send] { float: right; text-align: center;width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
.chat .send-area #message { width: 90%; padding: 9px; }
#messages { width: 70%;float: left; list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
[data-online] { float: right; background: #d9d9d9; width: 30%; }
.clr { clear: both; }
</style>
</head>
<body>
<div class="pages">
<a href="#" data-close>Close</a>
<div class="user_capture">
<label for="username">Your Name: *</label><br/>
<input id="username" type="text" value="" name="username" /><br/>
<label for="email">Email: *</label><br/>
<input id="email" value="" name="email_address" /><br/>
<label for="phone">Phone:</label><br/>
<input id="phone" value="" name="phone" /><br/>
<label for="question">Question: </label><br/>
<textarea id="question" name="question">
</textarea><br/><br/>
<a href="#" data-user-capture>Chat</a>
</div>
<div class="chat">
<div data-status></div>
<ul id="messages"></ul>
<ul data-online>
</ul>
<div class="clr"></div>
<div class="send-area">
<input id="message" autocomplete="off" /><a href="" data-send>Send</a>
</div>
</div>
</div>
<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>
$(document).ready(function(){
var socket = io.connect();
var $close = $('[data-close]');
$close.unbind().bind('click', function(){
if(window.confirm("Are you sure?")) {
location.reload();
}
});
//CAPTURE
$('[data-user-capture]').unbind().bind('click', function(e){
e.preventDefault();
//hide form show chat window
$('.user_capture').hide();
$('.chat').show();
var data = {
username:$('[name="username"]').val(),
question:$('[name="question"]').val(),
}
socket.emit('user capture', data);
});
socket.on('user capture', function(data){
$('#messages').append('<li><strong>'+data.username +' says: </strong>'+data.question+'<li>');
console.log(JSON.stringify(data));
$('[data-status]').append('<strong>Status: </strong>'+data.status);
//$('[data-online]').each(data.online_users).append('<li>'+online+'</li>')
});
//SEND MESSAGE
$('[data-send]').unbind().bind('click', function(e){
e.preventDefault();
if(!$('#message').val()){
$('#message').focus();
$('#message').attr('placeholder', 'Please enter a message...');
} else {
socket.emit('send', $('#message').val());
$('#message').val('');
// return false;
}
});
socket.on('send', function(data){
$('#messages').append('<li><strong>'+data.username +' says: </strong>'+data.msg+'<li>');
});
});
</script>
</body>
</html>
index.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io').listen(http);
var username;
var online_users = [];
var status = 'Disconnected';
app.get('', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
socket.on('user capture', function(data){
socket.username = data.username;
data.online_users.push(socket.username);
data.status = 'Connected';
io.emit('user capture', data);
console.log(data);
});
socket.on('send', function(msg){
sendData = {
msg:msg,
username:socket.username
};
io.sockets.emit('send', sendData);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});

NodeJS and socket.io can't send messages

server:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var clients = [];
var sequence = 1;
io.on('connection', function(socket){
console.log('Client connected (id=' + socket.id + ').');
clients.push(socket);
socket.on('login', function(msg){
console.log(msg);
io.emit('login', msg);
});
socket.on('disconnect', function(){
var index = clients.indexOf(socket);
if (index != -1) {
clients.splice(index, 1);
console.info('Client gone (id=' + socket.id + ').');
}
});
});
http.listen(3011, function(){
console.log('listening on *:3011');
});
client:
<!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>
var socket = io('http://localhost:3011');
$('form').submit(function(){
socket.emit('login', $('#m').val());
$('#m').val('');
return false;
});
socket.on('login', function(msg){
//alert(msg);
$('#messages').append($('<li>').text(msg));
});
socket.on('connect', function() {
console.log('connected');
});
socket.on('message', function(msg){
console.log(msg);
});
socket.on('disconnect', function() {
console.log('disconnected');
});
socket.on('error', function (e) {
console.log('System', e ? e : 'A unknown error occurred');
});
</script>
</body>
</html>
This work perfect on localhost.
server log:
listening on *:3011
Client connected (id=Kk-LUoJep5Uw0qWLAAAA).
message
Client gone (id=Kk-LUoJep5Uw0qWLAAAA).
But if i work with ec2 server. NodeJS and socket.io can't send message.
log ec2 server:
listening on *:3011
Client connected (id=1Phd18CNKLEnRH3LAAAA).
Client gone (id=1Phd18CNKLEnRH3LAAAA).
Port 3011 open.
he is get connect and disconnect event, but cant get or send message.
How to fix it? Thx.

Chat with express.io

I have two files, one named index.js and the other index.html.
When I press the send button the message doesn't appear
The code of the file index.js is the following:
app = require('express.io') ();
app.http().io();
app.get('/', function(req, res){
res.sendfile('index.html');
});
app.io.on('connection', function(socket){
socket.on('chat message',function(msg) {
app.io.emit('chat message' ,msg)
});
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
app.listen(3000);
The code of the file index.html is the following:
<!doctype html>
<html>
<head>
<title>Example of 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>
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>
</body>
</html>
write this instead
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(3000);
app.get('/', function (req, res) {
res.sendfile('index.html');
});
io.on('connection', function (socket) {
socket.on('chat message', function (data) {
socket.broadcast.emit('chat message',data);
});
});

Resources