【发布时间】:2017-04-17 14:12:40
【问题描述】:
我有一个服务器 app.js 和多个可以连接到我的服务器的客户端。我在 index.html 中显示服务器对客户端所说的内容,但我想在客户端与其交谈时对服务器执行相同的操作,并且 在 HTML 页面中显示我的客户端对服务器所说的内容。现在我用console.log()显示它
这是我的代码,我正在使用 Socket.io:(我是 Javascript 新手,这只是一个测试,所以这真的很简单)
app.js / 服务器:
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>
【问题讨论】:
标签: javascript html node.js socket.io console