socket.io - 用户连接或断开连接时打印消息

时间:2017-01-19 22:03:02

标签: node.js sockets

我是socket.io或node.js的新手,所以我想知道如何在用户连接或断开连接时将消息打印到聊天中。在搜索这个网站时,一些答案不起作用,其他答案不适用于我的情景,因此无法正常工作 的 Index.js

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

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

io.on('connection', function(socket){
socket.on('chat message', function(msg){
    io.emit('chat message', msg);
});
});

http.listen(8080, function(){
console.log('listening on *:8080');
});

的index.html

<!doctype html>
<html>
  <head>
    <title>Derpzy.ML</title>
    <style>
  * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
  form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
  form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
  form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
  #messages { list-style-type: none; margin: 0; padding: 0; }
  #messages li { padding: 5px 10px; }
  #messages li:nth-child(odd) { background: #eee; }
</style>
<link rel="icon" type="image/png" href="favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="favicon-16x16.png" sizes="16x16" />
  </head>
  <body>
<ul id="messages"></ul>
<form action="">
  <input id="m" autocomplete="off" /><button>Send</button>
</form>
<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();
$('form').submit(function(){
    socket.emit('chat message', $('#m').val());
    $('#m').val('');
    return false;
});
socket.on('chat message', function(msg){
   $('#messages').append($('<li>').text(msg));
});
</script>
  </body>
</html>

1 个答案:

答案 0 :(得分:2)

尚未测试,但您会想要做这样的事情。

服务器端:

//when socket is connected
io.on('connection', function(socket){

    console.log('Yay, connection was recorded')

    //emit message to all front-end clients
    io.emit('chat message', 'some message sent to all users');

    //handling disconnects
    socket.on('disconnect', function() {
       io.emit('chat message', 'some user disconnected');
    });

});

客户方:

//on io.emit from backend (notice 'chat message' event has same name as server side)
socket.on('chat message', function(msg){

   console.log('Yay, I got a message back from the server: ', msg)

   //handle the message however you would like
   $('#messages').append($('<li>').text(msg));

});

要测试服务器,您可以在“连接”回调中使用console.log,以确保后端正在接收连接。

要测试客户端,您可以在“聊天消息”回调中控制日志以确保正在接收数据。此外,请务必检查您的开发人员控制台,以确保错误与您尝试将数据附加到DOM的方式无关。