Socket.io页面到页面

时间:2017-10-25 07:37:58

标签: socket.io

此问题在此处和通过Google进行了大量搜索。 Socket.io的例子变化很大,而且(对于我的非专家)令人困惑。

我想使用Node.js和Socket.io通过服务器将数据从一个页面发送到另一个页面。我不希望服务器为页面提供服务,只是将数据从一个页面传送到另一个页面。作为第一步,我只想要一个基本页面来连接并发送一些文本。

对于服务器,我使用以下内容接收:

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

// Show a message in the console if anything connects to this server.
io.on('connection', function(socket){
     console.log('a user connected');
     });

// Listen on port 1337 and show this is happening by adding a message in
// the console.
http.listen(1337, function(){
           console.log('listening on *:1337');
           });

// If a message of type 'message' is receive display the content of
// the message.
io.on('message', function(message) {
     console.log(message);       
     });

对于第一个(来源)页面,我正在使用:

<!DOCTYPE html>
  <html>
    <head>
      <meta charset="utf-8" />
      <title>Socket.io Test</title>
    </head>

    <body>
      <h1>Communication with socket.io</h1>
      <script src="/socket.io/socket.io.js"></script>
      <script>

        // Connect to the server on port 1337.
        var socket = io.connect('http://localhost:1337');

        // Send a message of type 'message'.
        socket.emit('message', "Test");

      </script>
    </body>
 </html>

我可能只是天真和/或被所有socket.io示例混淆(或者只是很厚)但它似乎没有连接(即,没有&#39;用户连接&# 39;服务器控制台中的消息。)

非常感谢任何建议/意见。

老实说,我已经把它搜死了!

谢谢,

0 个答案:

没有答案