This is my server.js code:
var express =require('express'),
http = require('http');
var app= express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
users = [];
connections = [];
server.listen(process.env.Port || 3000);
console.log('server running ...')
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket){
connections.push(socket);
console.log('Connected: %s sockets connected', connections.length);
socket.on('disconnect',function(data){
users.splice(users.indexOf(socket.username),1);
updateUsernames();
connections.splice(connections.indexOf(socket),1);
console.log('Disconnected: %s sockets conected', connections.length);
});
//send message
socket.on('send message', function(data){
console.log(data)
io.sockets.emit('new message',{msg: data, user: socket.username});
});
//new User
socket.on('new user', function(data,callback){
callback(true);
socket.username = data;
users.push(socket.username);
updateUsernames();
});
function updateUsernames(){
io.sockets.emit('get users', users)
}
});
Here is my html file:
<!DOCTYPE html>
<html>
<head>
<title>IO chat</title>
<link rel = "stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<style >
body{
margin-top: 30px;
}
#messageArea{
display: none;
}
</style>
</head>
<body>
<div class = "container">
<div id = "userFormArea" class= "row">
<div class = "col-md-12">
<form id = "userForm">
<div class = "form-group">
<label>Enter Username</label>
<input class = "form-control" id = "username">
<br/>
<input type="submit" class = "btn btn-primary" value = " Login"/>
</div>
</form>
</div>
</div>
<div class = "row" id = "messageArea">
<div class = "col-md-4">
<div class = "well">
<h3> Online users </h3>
<ul class = "list-group" id = "users"> </ul>
</div>
</div>
<div class = "col-md-8">
<div class="chat" id = "chat"> </div>
<form id = "messageForm">
<div class = "form-group">
<label>Enter Message</label>
<textarea class = "form-control" id = "message"> </textarea>
<br/>
<input type="submit" class = "btn btn-primary" value = "Send Message"/>
</div>
</form>
</div>
</div>
</div>
<script>
$(function(){
var socket = io.connect();
var $messageForm = $('#messageForm');
var $message = $('#message');
var $chat = $('#chat');
var $userFormArea = $('#userFormArea');
var $userForm = $('#userForm');
var $messageArea = $('#messageArea');
var $users = $('#users');
var $username = $('#username');
$messageForm.submit(function(e){
e.preventDefault();
socket.emit('send message', $message.val());
$message.val('');
});
socket.on('new message', function(data){
$chat.append('<div class = "well"><strong>'+data.user+'</strong>:' + data.msg + '<div>');
});
$userForm.submit(function(e){
e.preventDefault();
socket.emit('new user', $username.val(),function(data){
if(data){
$userFormArea.hide();
$messageArea.show();
}
});
$username.val('');
});
socket.on('get users', function(data){
var html = '';
for (i = 0; i< data.length; i++){
html +='<li class = "list-group-item" >' + data[i]+ '</li>';
}
$users.html(html);
});
});
</script>
</body>
</html>
I've been struggling for this for a while, is it something wrong with socket.io? Or is it something that I am doing wrong.
If there's something different I have to do, please let me know. I literally connect to the socket, and it spews out console logs.
As you can see in the picture, I want it to say Connected: 1 sockets connected after ONE person connections.
This usually occurs when client and server are using different versions of socket.io. Check the version of server from package.json and give client the same version. I had the same issue and upgrading to socket.io version 2.1.1 fixed it.
Related
Please help me when i want to show message sender name near message, my data came undefined, message is sending successfuly but socket.nickname get undefined. How can i fix this problem. Can u help me ? I've been working on this for a very long time. I just couldn't realize where I was wrong. Finally I decided to seek help.
Server.js
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const users = {};
http.listen(8005, () =>{
console.log('8005 portu dinleniyor...');
});
io.sockets.on('connection', function (socket) {
socket.on('yeni-kullanici', function (data, callback) {
if (data in users){
callback(false);
} else {
callback(true);
socket.nickname = data;
users[socket.nickname] = socket;
updateUsers();
}
});
function updateUsers(){
io.sockets.emit('users', Object.keys(users));
}
updateUsers();
socket.on('mesaj-gonder', function (data) {
io.sockets.emit('mesaj', {msg: data, nick: socket.nickname});
});
socket.on('disconnect', (data) => {
if (!socket.nickname) return;
delete users[socket.nickname];
updateUsers();
});
});
client
import React, {Component} from 'react';
import io from "socket.io-client";
class Home extends Component {
constructor() {
super();
this.state = {
url:'http://127.0.0.1:8005'
}
}
kullaniciAl(e){
e.preventDefault();
const userName = $('#userName').val();
const socket = io(this.state.url);
socket.emit('yeni-kullanici', userName, function (data) {
if (data){
$('.giris').hide();
$('.chat').show();
}else{
$('.uyari').show();
$('#userName').val('');
}
});
}
yeniMesaj(e){
e.preventDefault();
const mesaj = $('#mesaj').val();
const socket = io(this.state.url);
socket.emit('mesaj-gonder', mesaj);
$('#mesaj').val('');
}
render() {
const socket = io(this.state.url);
socket.on('users', function (data) {
let html = '';
for(let i=0; i<data.length; i++){
html += data[i] + '<br/>';
}
$('#users').html(html);
});
socket.on('mesaj', function (data){
$('#contentMesaj').append('<b>' + data.nick + ': </b>' + data.msg + '<br/>');
});
return (
<div>
<div className="giris">
<div className="alert alert-danger uyari" role="alert" style={{display: "none"}}>
Bu kullanıcı adı zaten mevcut. Tekrar Deneyiniz...
</div>
<form>
<div className="form-group">
<label htmlFor="exampleInputEmail1">Kullanıcı Adı</label>
<input className="form-control" id="userName" placeholder="Kullanıcı adınızı girin..."/>
</div>
<button onClick={this.kullaniciAl.bind(this)} className="btn btn-primary">Gönder</button>
</form>
</div>
<div className="row chat" style={{display: "none"}}>
<div className="col-md-8" >
<div id="contentMesaj" style={{height: "500px",border:"1px solid"}}>
</div>
<div className="message">
<form>
<div className="input-group mb-3">
<input id="mesaj" className="form-control" placeholder="Mesajınızı Yazın..." aria-describedby="basic-addon2"/>
<div className="input-group-append">
<button onClick={this.yeniMesaj.bind(this)} className="btn btn-outline-secondary" type="button">Gönder</button>
</div>
</div>
</form>
</div>
</div>
<div className="col-md-4">
<div className="head col-md-12">
<h3>Kullanıcılar</h3>
</div>
<div className="kul col-md-12">
<span id="users"/>
</div>
</div>
</div>
</div>
);
}
}
export default Home;
Result SS :
Result SS :
I create a simple messenger web app with node express socket.io.
but the result of user name is undefined.(if i change user id,then it will work,but why?)
app.js
const app = express();
const http = require("http").createServer(app);
const io = require("socket.io")(http);
app.use(express.static(__dirname + "/"));
io.on("connection", socket => {
console.log("connected", socket.id);
socket.on("chat", data => {
console.log(data.name);
io.sockets.emit("chat", data);
});
});
http.listen("3000", () => {
console.log("messenger is on!");
});
index.html
<body class="container">
<div id="input">
<input type="text" id="nam" placeholder="what is your name?" /> // user name
<input type="text" id="message" placeholder="type your message..." />
<button onclick="clicked()" type="submit" class="btn btn-success" id="send">
send
</button>
</div>
<div id="contener">
<div id="output"></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.dev.js"></script>
<script>
var socket = io();
var nam = document.getElementById("nam");
var message = document.getElementById("message");
var send = document.getElementById("send");
var output = document.getElementById("output");
function clicked() {
socket.emit("chat", {
name: nam.value,
message: message.value
});
}
socket.on("chat", data => {
output.innerHTML += `<p>${data.name} <br> ${data.message}</p>`;
});
</script>
</body>
If I change all "nam" with "name",then It will not work! whyyy?
I don't know what's wrong.
Give it a try,by replace all nam with name
just replace all nam with name
<body class="container">
<div id="input">
<input type="text" id="name" placeholder="what is your name?" />
<input type="text" id="message" placeholder="type your message..." />
<button onclick="clicked()" type="submit" class="btn btn-success" id="send">
send
</button>
</div>
<div id="contener">
<div id="output"></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.dev.js"></script>
<script>
var socket = io();
var name = document.getElementById("name");
var message = document.getElementById("message");
var send = document.getElementById("send");
var output = document.getElementById("output");
function clicked() {
socket.emit("chat", {
name: name.value,
message: message.value
});
}
socket.on("chat", data => {
output.innerHTML += `<p>${data.name} <br> ${data.message}</p>`;
});
</script>
</body>
I am totally new in node.js and I want to create a simple phonebook app with express and postgresql. I want to have two pages, one to add a new contact and another one for contacts to be shown in an html table with the ability to update or delete rows. Until now I have implemented the insert but I don't know how to create the "contacts.html" page dynamically from database. Thank you in advance!
index.html
<header>
<ul>
<li><h2>Phonebook</h2></li>
<li>New Contact</li>
<li>Contacts</li>
</ul>
</header>
<section>
<form action="insertContact">
<p>Full Name</p>
<input type="text" name="fullname" required>
<p>Phone</p>
<input type="text" name="phone1" required>
<p>Mobile</p>
<input type="text" name="phone2">
<p>Address</p>
<input type="text" name="address" required> <br><br>
<input type="submit" name="submitBtn" id="submitBtn" value="Submit">
</form>
</section>
server.js
var express = require('express');
var path = require('path');
var db = require('pg');
var http = require('http');
var app = express();
app.use(express.static(path.join(__dirname,'/')));
var dbConnection = "postgres://postgres:root#localhost:5432/Phonebook";
app.get('/insertContact',function(req,res){
var dbClient = new db.Client(dbConnection);
dbClient.connect(function(err){
if(err)
throw err;
var query = "insert into Contacts (fullname,phone,mobile,address) values ($1,$2,$3,$4)";
var fullname = req.query.fullname;
var phone = req.query.phone1;
var mobile = req.query.phone2;
var address = req.query.address;
var contact = [fullname , phone , mobile , address];
dbClient.query(query , contact , function(err){
if(err)
throw err;
else {
console.log('Success!') ;
res.redirect('/');
res.end();
}
});
});
});
app.get('????',function(req,res) {
var dbClient = new db.Client(dbConnection);
dbClient.connect(function(err){
if(err)
throw err;
var query = "select * from Contacts";
dbClient.query(query,function(err,result){
if(err)
throw err;
else {
??????????
res.end();
}
});
});
});
app.listen(8080,function(){
console.log('Server started');
});
sample image
You can do that by using any javascript template language one of the most popular is EJS "embedded javascript" its very easy to integrate and use with node js
You simply create your template and pass any variable like an array.
Check the code below this is how you add a template in EJS
<html >
<head>
<meta charset="utf-8">
</head>
<body>
<section class="home">
<h1>Contacts list</h1>
<ul class="list-group">
<% for(var i=0; i<contacts.length; i++) {%>
<li class="list-group-item">
<span>Name: </span><%= contacts[i].name %>
<br/>
<span>Phone: </span><%= contacts[i].phone %>
</li>
<% } %>
</ul>
</section>
</body>
</html>
Then in your node js route handler will just render that template and pass the required data.
app.get('????',function(req,res) {
var dbClient = new db.Client(dbConnection);
dbClient.connect(function(err){
if(err)
throw err;
var query = "select * from Contacts";
dbClient.query(query,function(err,result){
if(err)
throw err;
else {
res.render('contacts.ejs', { contacts: result });
}
});
});
});
One final step is to tell node that it will use ejs as template language.
app.set('view engine', 'ejs');
And don't forget to npm install --save ejs
Thanks to Amr Labib's help
server.js
var express = require('express');
var path = require('path');
var db = require('pg');
var app = express();
app.use(express.static(path.join(__dirname,'/')));
app.set('view engine', 'ejs');
var dbConnection = "postgres://postgres:root#localhost:5432/Phonebook";
// Insert Contact
app.get('/insertContact',function(req,res){
var dbClient = new db.Client(dbConnection);
dbClient.connect(function(err){
if(err)
throw err;
var query = "insert into Contacts (fullname,phone,mobile,address) values ($1,$2,$3,$4)";
var fullname = req.query.fullname;
var phone = req.query.phone;
var mobile = req.query.mobile;
var address = req.query.address;
var contact = [fullname , phone , mobile , address];
dbClient.query(query , contact , function(err){
if(err)
throw err;
else {
console.log('Contact Inserted!') ;
res.redirect('/');
res.end();
}
});
});
});
// Form Handling - Update Row / Delete Row
app.get('/handleForm',function(req,res){
var dbClient = new db.Client(dbConnection);
dbClient.connect(function(err){
if(err)
throw err;
if(req.query.deleteBtn != null){
var query = "delete from Contacts where id = ($1)";
var id = [req.query.id];
dbClient.query(query , id , function(err){
if(err)
throw err;
else {
console.log('Contact Deleted!') ;
res.redirect('/contacts.html');
res.end();
}
});
} else if(req.query.updateBtn != null) {
var query = "update Contacts set fullname=($1),phone=($2),mobile=($3),address=($4) where phone=($5)";
var fullname = req.query.fullname;
var phone = req.query.phone;
var phoneHidden = req.query.phoneHidden;
var mobile = req.query.mobile;
var address = req.query.address;
dbClient.query(query , [fullname,phone,mobile,address,phoneHidden], function(err){
if(err)
throw err;
else {
console.log('Contact Updated!') ;
res.redirect('/contacts.html');
res.end();
}
});
}
});
});
// Search contact by phone
app.get('/searchContact',function(req,res) {
var dbClient = new db.Client(dbConnection);
dbClient.connect(function(err){
if(err)
throw err;
var query = "select * from Contacts where phone=($1)";
var searchBoxValue = req.query.searchBoxValue;
dbClient.query(query , [searchBoxValue], function(err,result){
if(err)
throw err;
else {
res.render('searchedContact.ejs' , {contacts: result});
res.end();
}
});
});
});
// Show Contact's Table
app.get('/contacts.html',function(req,res) {
var dbClient = new db.Client(dbConnection);
dbClient.connect(function(err){
if(err)
throw err;
var query = "select * from Contacts";
dbClient.query(query,function(err,result){
if(err)
throw err;
else {
res.render('contacts.ejs', { contacts: result });
res.end();
}
});
});
});
app.listen(8080,function(){
console.log('Server started');
});
contacts.ejs
<section id="table">
<div class="table">
<div id="headers">
<span id="id">id</span>
<span id="fullname">Name</span>
<span id="phone">Phone</span>
<span id="mobile">Mobile</span>
<span id="address">Address</span>
</div>
<% for(var i = 0; i < contacts.rows.length; i++) { %>
<form class="tr" action="handleForm">
<input type="text" id="id" name="id" class="td" readonly value= <%= contacts.rows[i].id %>>
<input type="text" name="fullname" class="td" value= <%= contacts.rows[i].fullname %>>
<input type="text" name="phone" class="td" value= <%= contacts.rows[i].phone %>>
<input type="text" name="mobile" class="td" value= <%= contacts.rows[i].mobile %>>
<input type="text" name="address" class="td" value= <%= contacts.rows[i].address %>>
<input type="submit" name="updateBtn" id="updateBtn" value="update" class="td">
<input type="submit" name="deleteBtn" id="deleteBtn" value="delete" class="td">
<input type="hidden" name="phoneHidden" id="phoneHidden" class="td" value=<%= contacts.rows[i].phone %> >
</form>
<% } %>
</div>
</section>
I'm new to NodeJs. Now I'm trying socket.io. I want to build website like Zopim(https://www.zopim.com/). Now I'm struggling with : client(A) should get helpline from one admin only and to prevent other admins to chat with client(A).
This is server.js
var app = require('express')();
var bodyParser = require('body-parser');
var mysql = require("mysql");
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(require("express").static('data'));
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
/* Creating MySQL connection.*/
var con = mysql.createPool({
host : 'localhost',
user : 'root',
password : '',
database :'Chat_tryout'
});
var insertRecord = 'Insert into mytable(socketid,receiver,message)value(?,?,?)';
app.get("/",function(req,res){
res.sendFile(__dirname + '/index.html');
});
var msg={};
io.on('connection', function(socket){
console.log(socket.id + "connected");
socket.on('message',function(msg){
console.log('user' +this.id+ 'sent message"'+ msg +'"');
//console.log(" admin id " + io.sockets.connected[socketid]);
con.getConnection(function(err, connection) {
var message=msg;
var socketid=" ";
con.query( insertRecord,[socketid,socket.id,msg], function(err, res) {
if(err){
console.log("error:" + err);
}else
console.log ("inserted"+ socket.id +"message"+ msg);
//res.end(``);
});
});
app.post('/get_data', function (req, res) {
var msg=req.body.name;
var toid = req.body.toid;
//var socketid = this.socket.sessionid;
//console.log(socketid);
console.log(toid);
io.to(toid).emit('mymessage',msg);
con.getConnection(function(err,connection){
var message=msg;
con.query( insertRecord,[socketid,toid,msg], function(err, res) {
if(err){
console.log("error:" + err);
}else
console.log ( "inserted "+ socket.id +" message "+ msg);
});
});
});
});
socket.on('disconnect', function() {
console.log('client socketio disconnect!');
});
app.get('/api/getalldata', function(req,res){
con.getConnection(function(err,connection){
con.query( 'select * from mytable', function(err, rows) {
if(err){
console.log("error:" + err);
}else
console.log ("success");
res.json(rows);
});
});
});
});
http.listen(8080,function(){
console.log("Listening on http://127.0.0.1:8080/");
});
Index.html :
(ADMIN PAGE)
<html ng-app="sample">
<head>
<title>Connecting Node.js app to MySql</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script type="text/javascript">
var app = angular.module('sample',[]);
app.controller('sample', function ($scope,$http,$timeout) {
$scope.data_server={};
$scope.socketid={};
var TypeTimer;
var TypingInterval = 1000;
$scope.keyup = function() {
$timeout.cancel(TypeTimer);
TypeTimer=$timeout( function(){ get_data(); }, TypingInterval);
};
$scope.keydown = function(){
$timeout.cancel(TypeTimer);
};
function get_data(){
var name=$scope.name;
var toid = $scope.toid;
$http.post('/get_data',{name:name,toid:toid}).success(function(data, status, headers, config) {
// $scope.data_server=data;
}).error(function(data, status) {
//alert("Connection Error");
});
}
$scope.getalldata = function(){
$http.get('/api/getalldata')
.success(function(data) {
$scope.data_server = data;
// console.log(data);
})
.error(function(err) {
console.log('Error: ' + err);
});
};
});
</script>
</head>
<body ng-controller="sample">
<div class="container">
<div id="name-group" class="form-group">
<h2>ADMIN</h2>
<ul id="messages"></ul>
<br/>
<input type="text" class="form-control" ng-model="name" placeholder="Type here and check the Title in Tab"/>
<input type="text" class="form-control" ng-model="toid" ng-keyup="keyup()" ng-keydown="keydown()" ng-blur="blur()" ng-change="change()"/>
{{toid}}
<br/>
</div>
<div class="table-responsive">
<table class="table table-hover"ng-repeat="data in data_server" >
<thead>
<tr>
<th>From</th>
<th>Message</th>
</thead>
<tbody>
<tr>
<td>{{data.receiver}}</td>
<td>{{data.message}}</td>
<!-- <td><input type="text" value="{{data.receiver}}"><td>
<td><input type="text" ng-model="reply" ng-keyup="submit()"></td>-->
</tr>
</tbody>
</table>
</div>
<div class="rows">
<div class="col-md-12">
<div class="data" >
<!---{{ data_server}}--->
<hr/>
</div>
<div ng-show="data_server.length == 0" >
<div class="alert alert-info" >
<p class="text-center" >
Sorry, Right now we don't have any results for you.
</p >
</div >
</div >
</div>
</div>
<div class="rows">
<button class="btn btn primary" ng-click="getalldata()">Get Messages</button>
<div class="form-row form-last-row">
</div>
</div>
</div>
</body>
<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.connect("http://localhost:8080");
socket.on('message', function(msg){
$('#messages').append($('<li>').text(msg));
});
I'm having html front end for client where they emit and receive messages using:
var socket = io.connect("http://localhost:8080");
$('form').submit(function(){
socket.emit('message', $('#message').val());
$('#message').val('');
return false;
});
socket.on('mymessage', function(msg){
$('#messages').append($('<li>').text(msg));
});
near time . I try write chat app using node Js and Socket.io , i have 1 page login.html , 1 page chat.html and server.js file . When i login with UserA, i will send email and pass to server and verify it . After , go to page chat.html . Here , i show list user , but when i try refresh page chat.html , socket.id changed . I have solution save socket.id after refresh in database MongoDb , but when i log in with UserB other browser , and after refresh page of UserA , but socket.id of UserB changed , not User A . Sorry for my English.
This is login.html page
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<body>
<div class="container">
<form class="form-signin" id="formLogin">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" placeholder="Email address" required="" autofocus="">
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control" placeholder="Password" required="">
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div> <!-- /container -->
<script type="text/javascript">
jQuery(function ($){
var socket= io.connect('http://localhost:8080');
var $email =$('#inputEmail'),
$password=$('#inputPassword'),
$login=$('#formLogin');
$login.submit(function (event){
socket.emit('login', { email:$email.val(), password:$password.val()});
socket.on('CheckLogin', function (data){
console.log('show something');
if(data){
console.log(data);
window.location.href='chat';
}else {
alert('Tai khoan hoac mat khau khong dung');
}
});
/* ,function (data){
console.log(data);
if(data){
console.log('Login successfuly');
window.location.href = "chat";
socket.on('sendId', function(data){
console.log(data[0]._id);
});
}else {
console.log('Login faile');
}
}*/
event.preventDefault();
});
});
</script>
</body>
</html>
This is server.js file
var app = require('express')(),
server = require('http').Server(app),
io=require('socket.io')(server),
mongoose=require('mongoose');
server.listen(8080);
var mongoURL = 'mongodb://localhost/ChatDatabase';
app.get('/login', function(req, res){
res.sendFile(__dirname+'/signin.html');
});
var emailprecentLogin='';
var namePreLogin = '';
var logInStatus = false;
var Users= mongoose.model('Users',{
email :String,
name:String,
password:String,
socketId :String
});
var Messages = mongoose.model('Messages',{
name :String,
message:String
});
/*list variable*/
var mailLogin = '';
var statusLogin = false ;
var listLogin =[];
mongoose.connect(mongoURL , function(err, db){
if(err){
console.log('Connect err');
}else {
console.log('Connect successfuly');
/*get value send from loginform and verify*/
io.on('connection', function (socket){
socket.on('login', function (data){
var tmpEmail = data.email ;
var tmpPass= data.password ;
mailLogin = data.email;
console.log('info login' + tmpEmail + tmpPass);
Users.findOne({ email:tmpEmail, password:tmpPass }).exec(function(err , docs){
if(docs==null){
console.log(err +typeof(docs));
socket.emit('CheckLogin', false);
}else {
if(docs.email == tmpEmail && docs.password==tmpPass){
statusLogin=true;
socket.emit('CheckLogin', true);
console.log('Info of user login:'+docs + typeof(docs));
app.get('/chat', function (req, res){
res.sendFile(__dirname+'/chat.html');
});
}
}
});
});/*end verify login*/
socket.emit('tmpEmailLogin',mailLogin );
/*update socket id when user f5 or refresh page*/
socket.on('connectServer', function(data){
/*console.log(data);*/
console.log('User F5'+data);
var tmpSocketId = socket.id ;
var tmpLogin = data;
Users.update({email:data},{$set:{socketId:tmpSocketId}},function (err, userUpdate){
if(err){
/*console.log(err);*/
console.log("err sendSocketID");
}else {
Users.find({}).exec(function(err, docs){
if(err){
console.log('Err find list user');
}else {
socket.emit('listUser', docs);
}
});
Users.find({email:mailLogin}).exec(function(err, docs){
if(err){
console.log('Err find list user');
}else {
console.log('Updated socketId');
/*console.log(docs);*/
}
});
}
});
});
/*update socket when user click item*/
socket.on('updateSocketId', function(data){
Console.log('user f5 :' + mailLogin);
});
});
}
});
This is chat.html file
<!DOCTYPE html>
<!-- saved from url=(0040)http://getbootstrap.com/examples/signin/ -->
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="http://getbootstrap.com/favicon.ico">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" >
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css" >
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<title>Chat</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<style type="text/css">
#viewContent{
color: black ;
height: 400px;
background-color: #F5F5F5;
overflow: scroll;
}
#listUser{
height: 400px;
}
</style>
</head>
<body>
<div id='header'>
<h2 class="title">This is chat box</h2>
</div>
<div id='content' >
<div id='listUser' class='col-md-4'>
<li id ='list' class = "list-group-item active">List User</li>
</div>
<div name='chatbox' class='col-md-8'>
<li id ='yourname' class = "list-group-item active">Your Name</li>
<div id='viewContent'></div>
<div name='formInput' >
<form class='' id='formChat'>
<div class="form-group">
<label class="sr-only" for="contentChat">Enter message</label>
<input type="text" class="form-control" id="contentChat" placeholder="Enter message" />
<input type='submit' class='btn btn-primary ' value ='Send'/>
</div>
</form>
</div>
</div> <!-- chat box div -->
</div>
<script type="text/javascript">
jQuery(function($){
var socket = io.connect('http://localhost:8080');
var $contentChat = $('#contentChat'),
$send =$('formChat');
var tmpEmailLogin;
var listID = [];
var idSocket='' ;
var emailPre= '';/*user login precent*/
var tenLogin ='';
var value_id ='';
/*<----------- chat
send list user form server
set connect 2 user
show message
------------->*/
/* socket.on('infoLogin', function(docs){
emailPre=docs ;
});*/
/*send list user */
socket.on('tmpEmailLogin', function(data){
tmpEmailLogin = data;
/*console.log(data);*/
socket.emit('connectServer',tmpEmailLogin); /*gửi socket để set socketId lên database*/
});
/*console.log('user login :' +tmpEmailLogin);*/
socket.on('listUser', function(data){/* show list user in database*/
console.log('socketId listUser :' + socket.id);
var j = 0 ;
/*console.log('Email login:' +emailPre);*/
$('#listUser').empty();
for(var i =0 ; i<data.length; i++){
$('#listUser').append('' +data[i].name+ '');
}
});
var click = 0 ;
$(document).on('click', 'a.list-group-item', function(event){
click ++;
$('#viewContent').innerHTML='';
if(click =1){
$('a.list-group-item').each(function(i , obj){
this.setAttribute("class", " list-group-item");
click = 0 ;
$('#viewContent').empty();
});
}
/*emailLogin=this.id;*/
var reqIdOfEmail = this.id;
this.setAttribute("class", " list-group-item active");
socket.emit('updateSocketId', reqIdOfEmail);
socket.on('ResSocket', function (data){
idSocket = data.idSk;
nameOfSk = data.nameReq ;
console.log(nameOfSk+idSocket );
});
event.preventDefault();
}); /* end click*/
$('#formChat').submit(function(event){
var $contentMsg = $('#contentChat').val();
/*alert($contentMsg);*/
if(idSocket!=''&& idSocket!=null){
socket.emit('SendMsg', {idsocket:idSocket, msg:$contentMsg, name:tenLogin})
}
event.preventDefault();
});
/*P2P message*/
socket.on('P2Pmessage', function (data){
/*var nameReq= data.name;*/
console.log('show something here');
var msgContent=data.content;
$('#viewContent').append('<b></b>'+msgContent +'<br>' );
});
});
</script>
</body>
</html>
You can join your users to same room,
So even if socketId will change
they can send and receive messages.
In connection you join room with this code:
io.on('connection', function(socket){
socket.join('some room');
});
And send message to room:
io.to('some room').emit('some event'):
You can find more documentation here.