I have a server app.js and multiple clients that can connect to my server. I display what the server say to the client in an index.html , but I want to do the same for the server when the client is talking to it, and display what my client says to the server in an HTML page. Right now I'm displaying it with console.log()
Here's my code, I'm using Socket.io : (I'm new to Javascript, this is just a test, so this is really simple )
app.js / Server :
var http = require('http'),
fs = require('fs'),
// NEVER use a Sync function except at start-up!
index = fs.readFileSync(__dirname + '/index.html');
// Send index.html to all requests
var app = http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(index);
});
// Socket.io server listens to our app
var io = require('socket.io').listen(app);
// Send current time to all connected clients
function sendTime() {
io.emit('clearance', { time: new Date().toJSON() });
}
// Send current time every 10 secs
setInterval(sendTime, 10000);
// Emit welcome message on connection
io.on('connection', function (socket) {
// Use socket to communicate with this particular client only, sending it it's own id
socket.emit('welcome', { message: 'Welcome!', id: socket.id });
socket.on('i am client', console.log);
socket.on('receiveClerance', function (data) {
console.log(data);
});
});
app.listen(3000);
Index.html
<!doctype html>
<html>
<head>
<script src='/socket.io/socket.io.js'></script>
<script>
var socket = io();
var data = "";
socket.on('welcome', function(data) {
addMessage(data.message);
// Respond with a message including this clients' id sent from the server
socket.emit('i am client', {data: 'foo!', id: data.id});
});
socket.on('clearance', function (data) {
addMessage(data.time + data);
$data = data;
});
socket.on('message', console.log.bind(console));
function addMessage(message) {
var text = document.createTextNode(message),
el = document.createElement('li'),
messages = document.getElementById('messages');
el.appendChild(text);
messages.appendChild(el);
var btn = document.createElement("BUTTON");
btn.textContent = "Test";
btn.onclick = function () {
socket.emit('receiveClerance', "La clerance " + $data + " est recu");
}
messages.appendChild(btn);
}
</script>
</head>
<body>
<ul id='messages'></ul>
</body>
</html>