Express not doing anything but sending HTML file - javascript

I'm using an app.post method in Express like so:
app.post('/race', function(req,res) {
let raceResponse = {
user_name: req.body.userName
}
console.log('Express has received race.');
//Socket.IO
let race = io.of('/race').on('connection', (socket) => {
console.log('A user has entered the race!');
socket.on('racePageReady', function() {
console.log('race page ready recieved');
socket.emit('racePageInfo', raceResponse);
});
socket.on('createRoom', function(roomName) {
socket.join(roomName);
let clients = io.sockets.adapter.rooms[roomName].sockets;
console.log("A room with the name " + roomName + "was created.");
console.log(clients);
socket.emit('roomCreated', clients);
});
socket.on('joinRoom', function(roomName) {
socket.join(roomName);
let clients = io.sockets.adapter.rooms[roomName].sockets;
console.log('A user joined the room with the name: ' + roomName + ". The user's name is " + raceResponse.user_name);
console.log(clients);
socket.emit('roomCreated', clients);
});
});
res.sendFile(path.join(__dirname, '/client/race/index.html'));
}
The page is being sent fine, but the console.log and all the other Socket.IO stuff just doesn't happen. I'm finding this peculiar, because I have a different app.post method that works just fine, all console.logging and Socket.IO business happens. Here's the code:
app.post('/city', function(req,res) {
let cityResponse = {
user_name: req.body.userName
}
console.log('Express has received city.');
//Socket.IO
let city = io.of('/city').on('connection', (socket) => {
socket.id = Math.random();
socket.name = cityResponse.user_name;
SOCKET_LIST[socket.id] = socket; //defined earlier
User.onConnect(socket); //defined earlier
socket.on('cityPageReady', function() {
socket.emit('cityPageInfo', cityResponse);
console.log('city page ready recieved');
});
console.log('A user has connected to the city!');
console.log("Socket: " + socket);
console.log("Socket ID: " + socket.id);
console.log("SOCKET_LIST: ");
console.log(SOCKET_LIST);
socket.on('chat message', function(msg, user) {
console.log('User ' + user + ' sent the message : ' + msg);
socket.emit('chat message', msg, user);
});
});
res.sendFile(path.join(__dirname, '/client/city/index.html'));
});
As far as I can tell, both methods look pretty much the same, except for the Socket.IO stuff in the middle. I'm fairly certain that the io.of method is correct, as it's working for the City page, but not the race.
The only other difference is the way that the two pages are accessed. The City page is accessed through a HTML form with an action attribute, whereas the Race page is accessed through a HTML link (on the City page) with a href attribute.
Both methods are shown below:
CITY
<form id="cityForm" action="http://localhost:4000/city" method="POST">
User name: <input type="text" name="userName">
button type="submit" id="formSubmit">Submit</button>
</form>
RACE
<div><a href="http://localhost:4000/race"></div>
Can anyone see why this peculiar behaviour is occuring? If any other information is needed please let me know so that I can include it.

When clicking an on HTML link, the browser does a GET HTML request. When you submit a Form (with method="POST"), the browser does a POST request.
When using app.post(), you tell express to listen for POST requests. If you want express to listen for GET requests, you should use app.get()

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.io show amount of user connections

I got a very simple socket.io application where I'm able to see when a user connects to my site and when a user leaves. The first user is able to see everybody that gets in, however the second will only see the people coming in after him, and so on.... What I want the user that connects to see are all current connected users
Server.js
var io = require("socket.io")(http);
var users = [];
io.on("connection", function (socket) {
console.log("User connected", socket.id);
Some loop to see user connected I think?!
socket.on("user_connected", function (username) {
users[username] = socket.id;
console.log(users);
if (username !== 'null'){
io.emit("user_connected", username);
}
});
socket.on("send_message", function (data) {
io.emit("new_message", data);
});
socket.on("user_left", function (datan) {
io.emit("user_remove", datan);
console.log("user left", datan);
});
});
site.html
window.onbeforeunload = function () {
io.emit("user_left", name);
};
var name = <?php echo json_encode($_SESSION['displayname']); ?>;
var bild = <?php echo json_encode($_SESSION['userpic']);?>;
var dt = new Date();
var tid = dt.getHours() + ":" + dt.getMinutes();
io.emit("user_connected", name);
sender = name;
io.on("user_connected", function (username) {
var html = "";
html += "<li data-username='" + username + "'>" + username + "</li>";
document.getElementById("users").innerHTML += html;
});
Looked into this question, but me a dumb coder doesn't understand what 'my_room' is towards my soloution. Sorry for weird question, I'm just kind of lost
If you want to send a user list to everyone, create an object like users, add a record each time a user connected, and broadcast to everyone.
if someone disconnects, then first remove that from your collection then send only disconnected user's info to clients, so clients can delete that user from their list.
If all you want is total number of questions, just send io.sockets.clients().length

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

Why is client disconnecting and reconnecting in node + express + socket.io + jade simple app

I created a simple application as an attempt to integrate node, express, socket.io, and jade. The user enters some string ("tool ID") in a text field and clicks a submit button. That text is simply converted to all uppercase and the result is appended to the results section on the page. The results should be automatically updated for other clients viewing the page.
It mostly works. However the problem is that right after the user clicks the submit button on the page to submit the tool ID, the node console and browser javascript console both show the client disconnecting and then reconnecting.
To the user it looks like the results are updated correctly for a fraction of a second. Then the results go blank for another fraction of a second. Then the results are redisplayed. Since I am showing the user's session ID with the results, I can see that the session ID changes during the short time while the results go blank.
Note that if a different client is simply viewing the page, but not otherwise interacting, the results are updated smoothly (no brief time of results going blank) and that client doesn't seem to be disconnecting at all.
I don't want the client to disconnect and reconnect when they click the submit button on the form. Can someone tell me why this is happening and how I should be doing it properly?
My app.js (server)
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
io = require('socket.io').listen(server); // without the var, this becomes available to other files like routes.
var path = require('path');
var routes = require('./routes/routes');
var process = require('./routes/process');
var _ = require("underscore");
// all environments
app.set('port', 3097);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
//app.use(express.logger('dev'));
app.use(express.bodyParser()); //Tells server to support JSON, urlencoded, and multipart requests
app.use(express.methodOverride());
app.use(express.cookieParser('i7iir5b76ir857bveklfgf'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
var toolIDs = [];
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
io.on("connection", function(socket) {
console.log("Client connected. Sending Update");
socket.on("toolsRequest", function() {
socket.emit('toolsReady', {toolIDs: toolIDs}); //This should go to the client that just connected.
});
socket.on("disconnect", function() {
console.log("Client Disconnected");
});
socket.on("toolsUpdate", function(data) {
processedToolID = process.process(data.toolID);
toolIDs.push({id: data.id, inputToolID: data.toolID, outputToolID: processedToolID});
io.sockets.emit("toolsUpdated", {toolIDs: toolIDs}); //This should go to all clients
console.log('Results Updated - notifying all clients');
});
});
// display main page
app.get('/', routes.home);
server.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
My routes.js
/*
* GET home page.
*/
exports.home = function(req, res){
res.render('home', { title: 'Tool'});
console.log("Just called route.home");
};
My home.jade
doctype 5
html
head
title= title
link(rel='stylesheet', href='/bootstrap/css/bootstrap.min.css')
link(rel='stylesheet', href='/bootstrap/css/bootstrap-responsive.min.css')
script(src='/socket.io/socket.io.js')
script(src="http://code.jquery.com/jquery.min.js")
script(src='/js/index.js')
block content
#wrapper
h1
a(href='/') TOOL
#display
div.row-fluid
div.inlineBlock
form#toolForm
label Tool ID
input(type="text", placeholder="e.g. abc123")#toolID
span.help-block You may enter a string.
button(class="btn")#submit
| Submit
br
div.inlineBlock.topAligned
h2 Results
br
div#results
br
My index.js (client)
function init() {
/*
On client init, try to connect to the socket.IO server.
*/
var socket = io.connect('http://example.com:3097/');
//We'll save our session ID in a variable for later
var sessionID = '';
//Helper function to update the results
function updateResults(toolIDs) {
$('#results').html('');
for (var i = 0; i < toolIDs.length; i++) {
$('#results').append('<span id="' + toolIDs[i].id + '">' + '<b>Creator ID:</b> ' + toolIDs[i].id + ' <b>Your ID:</b> ' + sessionID + ' <b>Input Tool:</b> ' + toolIDs[i].inputToolID + ' <b>Output Tool:</b> ' + toolIDs[i].outputToolID + (toolIDs[i].id === sessionID ? '<b>(You)</b>' : '') + '<br /></span>');
}
}
/*
When the client successfully connects to the server, an
event "connect" is emitted.
*/
socket.on('connect', function () {
sessionID = socket.socket.sessionid;
// Note this appears in the browser Javascript console, not node console
console.log('You are connected as: ' + sessionID);
socket.emit('toolsRequest'); //Request the tools data so we can update results
});
socket.on('toolsReady', function(data) {
updateResults(data.toolIDs);
console.log('Results have been updated from socket.on.toolsReady');
});
socket.on('toolsUpdated', function (data) {
updateResults(data.toolIDs);
console.log('Results updated from socket.on.toolsUpdated');
});
/*
Log an error if unable to connect to server
*/
socket.on('error', function (reason) {
console.log('Unable to connect to server', reason);
});
function getCitations() {
var toolID = $('#toolID').val()
socket.emit('toolsUpdate', {id: sessionID, toolID: toolID});
}
$('#submit').on('click', getCitations);
}
$(document).on('ready', init);
Here's what I see in the node console when a client clicks the submit button:
debug - websocket writing 5:::{"name":"toolsUpdated","args":[{"toolIDs":[{"id":"5a1dfX2dmxcogYT_11e8","inputToolID":"a123123","outputToolID":"A123123"},{"id":"OIuqao6TsTeddQm111e-","inputToolID":"1abcdefg","outputToolID":"1ABCDEFG"},{"id":"Qr_YQ2ZhQHbDpBlk11e_","inputToolID":"abcdefg","outputToolID":"ABCDEFG"}]}]}
Results Updated - notifying all clients
Just called route.home
info - transport end (socket end)
debug - set close timeout for client Qr_YQ2ZhQHbDpBlk11e_
debug - cleared close timeout for client Qr_YQ2ZhQHbDpBlk11e_
debug - cleared heartbeat interval for client Qr_YQ2ZhQHbDpBlk11e_
Client Disconnected
debug - discarding transport
debug - served static content /socket.io.js
debug - client authorized
info - handshake authorized 2bPKGgmLdD4fp-vz11fA
debug - setting request GET /socket.io/1/websocket/2bPKGgmLdD4fp-vz11fA
debug - set heartbeat interval for client 2bPKGgmLdD4fp-vz11fA
debug - client authorized for
debug - websocket writing 1::
Client connected. Sending Update
debug - websocket writing 5:::{"name":"toolsReady","args":[{"toolIDs":[{"id":"5a1dfX2dmxcogYT_11e8","inputToolID":"a123123","outputToolID":"A123123"},{"id":"OIuqao6TsTeddQm111e-","inputToolID":"1abcdefg","outputToolID":"1ABCDEFG"},{"id":"Qr_YQ2ZhQHbDpBlk11e_","inputToolID":"abcdefg","outputToolID":"ABCDEFG"}]}]}
Thanks, I appreciate the help.
Your submit button is actually reloading the page, which is why the socket is disconnecting, and why you see the socket response for such a short time. Just prevent the default action of the submit button. Change this:
$('#submit').on('click', getCitations);
To something similar:
$('#submit').click(function(event) {
event.preventDefault();
getCitations();
});

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