2017-09-22 39 views
1

我正在写一个非常简单的应用程序(现在),我需要记录每个连接和断开div内。目前我可以记录我的控制台上的每个连接和断开连接的代码,但是对我有限的socket.io知识,我无法弄清楚如何在我的index.html文件 的div上登录它们,即我需要server.js发出(?)连接和断开连接,并将它们追加到div,而不是将它们记录在我的控制台上。 我包括我的server.js文件和我的html文件(其中包含客户端的脚本)。日志记录连接并断开连接socket.io

我server.js

var app = require('express')(); 
var server = require('http').Server(app); 
var io = require('socket.io')(server); 




app.get('/', function (req, res) { 
    res.sendFile(__dirname + '/index.html'); 
}); 

io.on('connection', function (socket) { 
    ID = socket.id; 
    console.log('client id - ' + socket.id + ' connected.'); 
    socket.on('disconnect', function() { 
     console.log('client id - ' + socket.id + ' disconnected.')}) 

}) 



server.listen(80, '95.211.186.223', function() { 
    console.log("Listening on 80") 
}); 

我的index.html

<!doctype html> 
<html lang="en"> 
<head></head> 
<body> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>  
    <script> 
     var socket = io.connect('http://95.211.186.223:80'); 
     socket.on('connect', function(data) { 
      console.log('ID: ' + socket.id) 
     }); 
    </script> 

    <div id="log"></div> 
</body> 
</html> 

回答

0

有落实,许多方面。只是其中之一:

在服务器:

io.on('connection', function (socket) { 
    ID = socket.id; 
    console.log('client id - ' + socket.id + ' connected.'); 
    io.sockets.emit('connect_event', data);  
}) 

io.on('disconnect', function() { 
    ID = socket.id; 
    console.log('client id - ' + socket.id + ' disconnected.'); 
    io.sockets.emit('disconnect_event', data); 
} 

如果你想知道如何发出一条消息给大家see the relevant question.

在客户端:

function addText(eventType) { 
    var p = document.createElement('p'); 
    p.innerHTML = 'ID: ' + socket.id + ' ' + eventType; 
    document.body.appendChild(p); 
} 
socket.on('connect_event', function(data) { 
    addText('connected') 
}); 
socket.on('disconnect_event', function(data) { 
    addText('disconnected') 
}); 
+0

也许我不是描述性不够。 这将给每个连接的socket.id打印出来。 我需要记录所有新连接和断开连接。不只是页面上的一个。 我认为server.js将不得不将这些数据发送到索引文件,以便每个新连接都附加到div而不是仅附加到一个。 –

+0

更新了答案。希望我正确地得到了你的问题。 – kurumkan

+0

是的。非常感谢你。 –