HTML按钮与节点服务器+ Socket.io通信

时间:2017-07-21 00:48:11

标签: node.js socket.io

当用户点击html按钮(#new)时,我想将他们的socket.id存储到我的节点服务器上的数组(userQueue)中,但是我无法弄清楚如何执行此操作。我是否需要设置发布请求或是否有通过socket.io的方法?

App.js(服务器):

// App setup
var express      = require('express'),
   socket        = require('socket.io'),
   app           = express(),
   bodyParser    = require("body-parser");

var server = app.listen(3000, function() {
   console.log('listening to requests on port 3000');
});
var io = socket(server);

app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static('public'));

// Room Logic
var userQueue = [];

io.on('connection', function(socket) {
   console.log('made socket connection', socket.id);

   socket.on('chat', function(data) {
      io.sockets.emit('chat', data);
   });

   socket.on('typing', function(data) {
      socket.broadcast.emit('typing', data);
   });

});

Chat.js(客户端):

// Make connection
 var socket = io.connect('http://localhost:3000');


// Query DOM
var message  = document.getElementById('message');
    handle   = document.getElementById('handle'),
    btn      = document.getElementById('send'),
    btnNew   = document.getElementById('new'),
    output   = document.getElementById('output'),
    feedback = document.getElementById('feedback');

// Emit events
btn.addEventListener('click', function(){
   socket.emit('chat', {
      message: message.value,
      handle: handle.value
   });
});

message.addEventListener('keypress', function() {
   socket.emit('typing', handle.value);
});

// Listen for events
socket.on('chat', function(data) {
   feedback.innerHTML = ""
   output.innerHTML += '<p><strong>' + data.handle + ':</strong>' + data.message + '</p>'
});

// Emit 'is typing'
socket.on('typing', function(data) {
   feedback.innerHTML = '<p><em>' + data + ' is typing a message...</em></p>'
});

的index.html:

<!DOCTYPE html>
<html>
<head>
   <title>WebSockets 101</title>
   <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
   <link rel="stylesheet" type="text/css" href="/styles.css">
</head>
<body>
   <div id="mario chat">
      <div id="chat-window">
         <div id="output"></div>
         <div id="feedback"></div>
      </div>
      <input id="handle" type="text" placeholder="Handle">
      <input id="message" type="text" placeholder="Message">
      <button id="send">Send</button>
      <button id="new">New</button>
   </div>
   <script type="text/javascript" src="/chat.js"></script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

我相信发布请求可能也会有效,但是如果你想简单地使用socket.io,可以考虑在你的chat.js中添加类似于聊天事件的内容:

btnNew.addEventListener('click', function() {
   socket.emit('new user', socket.id);
});

在服务器端,app.js

socket.on('new user', function(id) {
   userQueue.push(id);
});

它应该存储在数组中。希望这有帮助!