SocketIO:Node.js与浏览器客户端js的通信

时间:2018-10-06 19:22:20

标签: javascript node.js sockets server socket.io

我正在尝试在节点服务器和浏览器客户端之间双向发送数据。

我可以从节点服务器到浏览器客户端获取信息,反之亦然。我不明白我在做什么错,请帮忙。

节点server.js

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

app.use(express.static(__dirname + '/'))

http.listen(3000, function(){
  console.log('listening on http://127.0.0.1:3000');
});

// 1) Send initial data from node to browser
setInterval( function() {
  var msg = Math.random();
  socketTx.emit('Node', msg);
}, 1000);

var io = require('socket.io-client');
var socketRx = io.connect('http://localhost:3000', {reconnect: true});

// 4) Receive data from browser and log in node console
socketRx.on('Browser', function(msg){
  console.log(msg);
});

浏览器index.html

<html>
<head></head>

<body>
  <div id="message"></div>
  <script src="/socket.io/socket.io.js"></script>
  <script src="socket.js"></script>
</body>
</html>

浏览器socket.js

var socketRx = io();
var socketTx = io();

// 2) Receive initial data from node and display in browser
socketRx.on('Node', function(msg){
  document.getElementById("message").innerHTML = msg;

  // 3) Send data from browser back to node
  socketTx.emit('Browser', msg);
});

1 个答案:

答案 0 :(得分:0)

我对socket.io不太熟悉,如果有错误,请见谅。
通过引用this official document,我修复了server.js,如下所示。
在我的环境中,它一直运行良好。请尝试此代码。

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

app.use(express.static(__dirname + '/'))

http.listen(3000, function(){
  console.log('listening on http://127.0.0.1:3000');
});

// 1) Send initial data from node to browser
setInterval( function() {
  var msg = Math.random();
  socketTx.emit('Node', msg);
}, 1000);

var io = require('socket.io-client');
io.connect('http://localhost:3000', {reconnect: true});

// 4) Receive data from browser and log in node console
socketTx.on('connection', function(socket) {
  socket.on('Browser', function(msg){
    console.log(msg);
  });
});