【问题标题】:What is an example of the simplest possible Socket.io example?什么是最简单的 Socket.io 示例?
【发布时间】:2012-04-12 11:26:09
【问题描述】:

所以,我最近一直在尝试了解 Socket.io,但我并不是一个超级优秀的程序员,而且几乎我可以在网上找到的每个示例(相信我,我已经找了好几个小时),都有额外的东西使事情复杂化。很多例子都做了一堆让我感到困惑的事情,或者连接到一些奇怪的数据库,或者使用咖啡脚本或大量的 JS 库,让事情变得混乱。

我希望看到一个基本的、功能正常的示例,其中服务器每 10 秒向客户端发送一条消息,说明现在几点,然后客户端将该数据写入页面或发出警报,诸如此类很简单。然后我可以从那里弄清楚事情,添加我需要的东西,比如数据库连接等。是的,我已经检查了 socket.io 网站上的示例,它们对我不起作用,我不明白它们做了什么.

【问题讨论】:

标签: node.js socket.io


【解决方案1】:

编辑:我觉得任何人都最好在 Socket.IO 入门页面上咨询优秀的chat example。自从我提供了这个答案以来,API 已经非常简化。话虽如此,这里是为新 API 更新的小-小原始答案。

只是因为我今天感觉很好:

index.html

<!doctype html>
<html>
    <head>
        <script src='/socket.io/socket.io.js'></script>
        <script>
            var socket = io();

            socket.on('welcome', function(data) {
                addMessage(data.message);

                // Respond with a message including this clients' id sent from the server
                socket.emit('i am client', {data: 'foo!', id: data.id});
            });
            socket.on('time', function(data) {
                addMessage(data.time);
            });
            socket.on('error', console.error.bind(console));
            socket.on('message', console.log.bind(console));

            function addMessage(message) {
                var text = document.createTextNode(message),
                    el = document.createElement('li'),
                    messages = document.getElementById('messages');

                el.appendChild(text);
                messages.appendChild(el);
            }
        </script>
    </head>
    <body>
        <ul id='messages'></ul>
    </body>
</html>

app.js

var http = require('http'),
    fs = require('fs'),
    // NEVER use a Sync function except at start-up!
    index = fs.readFileSync(__dirname + '/index.html');

// Send index.html to all requests
var app = http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(index);
});

// Socket.io server listens to our app
var io = require('socket.io').listen(app);

// Send current time to all connected clients
function sendTime() {
    io.emit('time', { time: new Date().toJSON() });
}

// Send current time every 10 secs
setInterval(sendTime, 10000);

// Emit welcome message on connection
io.on('connection', function(socket) {
    // Use socket to communicate with this particular client only, sending it it's own id
    socket.emit('welcome', { message: 'Welcome!', id: socket.id });

    socket.on('i am client', console.log);
});

app.listen(3000);

【讨论】:

  • 非常感谢,这当然有效,更重要的是,我开始了解它是如何工作的。你写的真好,老实说,我确实花了至少 3 或 4 个小时试图让这一切正常工作,虽然很伤心,但哈哈。非常感谢莱纳斯!
  • 这对我不起作用。在浏览器中,我得到一个空白页面。在服务器端,除了“客户端授权”和“握手授权”之外没有任何输出。
  • @Boris 如果您在本地打开 index.html 文件,您可能会遇到这个问题。如果你这样做了,那么将脚本标签替换为 src="http://。如果你在 Web 服务器上托管,那么打开 javascript 控制台并尝试找出失败的原因。
  • 最初我得到'io not defined' - 我用这个代替
  • 你应该运行 "npm init" 然后通过 npm "npm install socket.io --save" 安装socket io
【解决方案2】:

这是我的提交!

如果您将此代码放入名为 hello.js 的文件中并使用节点 hello.js 运行它,它应该会打印出消息 hello,它已通过 2 个套接字发送。

代码显示了如何处理通过标记为 //Mirror 的代码部分从客户端反弹到服务器的 hello 消息的变量。

变量名是在本地声明的,而不是在顶部声明的,因为它们只在 cmets 之间的每个部分中使用。这些中的每一个都可以在一个单独的文件中并作为自己的节点运行。

// Server
var io1 = require('socket.io').listen(8321);

io1.on('connection', function(socket1) {
  socket1.on('bar', function(msg1) {
    console.log(msg1);
  });
});

// Mirror
var ioIn = require('socket.io').listen(8123);
var ioOut = require('socket.io-client');
var socketOut = ioOut.connect('http://localhost:8321');


ioIn.on('connection', function(socketIn) {
  socketIn.on('foo', function(msg) {
    socketOut.emit('bar', msg);
  });
});

// Client
var io2 = require('socket.io-client');
var socket2 = io2.connect('http://localhost:8123');

var msg2 = "hello";
socket2.emit('foo', msg2);

【讨论】:

  • 我认为这应该是公认的解决方案。至少帮助了我。
【解决方案3】:

也许这对你也有帮助。我在理解 socket.io 的工作原理时遇到了一些麻烦,所以我尽量简化了一个示例。

我根据此处发布的示例改编了这个示例:http://socket.io/get-started/chat/

首先,从一个空目录开始,并创建一个非常简单的文件,名为 package.json 将以下内容放入其中。

{
"dependencies": {}
}

接下来,在命令行中,使用 npm 安装本示例所需的依赖项

$ npm install --save express socket.io

这可能需要几分钟,具体取决于您的网络连接速度/CPU 等。要检查一切是否按计划进行,您可以再次查看 package.json 文件。 p>

$ cat package.json
{
  "dependencies": {
    "express": "~4.9.8",
    "socket.io": "~1.1.0"
  }
}

创建一个名为 server.js 的文件,这显然是我们由节点运行的服务器。将以下代码放入其中:

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

app.get('/', function(req, res){

  //send the index.html file for all requests
  res.sendFile(__dirname + '/index.html');

});

http.listen(3001, function(){

  console.log('listening on *:3001');

});

//for testing, we're just going to send data to the client every second
setInterval( function() {

  /*
    our message we want to send to the client: in this case it's just a random
    number that we generate on the server
  */
  var msg = Math.random();
  io.emit('message', msg);
  console.log (msg);

}, 1000);

创建最后一个名为 index.html 的文件并将以下代码放入其中。

<html>
<head></head>

<body>
  <div id="message"></div>

  <script src="/socket.io/socket.io.js"></script>
  <script>
    var socket = io();

    socket.on('message', function(msg){
      console.log(msg);
      document.getElementById("message").innerHTML = msg;
    });
  </script>
</body>
</html>

您现在可以测试这个非常简单的示例并看到类似于以下的一些输出:

$ node server.js
listening on *:3001
0.9575486415997148
0.7801907607354224
0.665313188219443
0.8101786421611905
0.890920243691653

如果您打开网络浏览器,并将其指向您正在运行节点进程的主机名,您应该会看到相同的数字出现在您的浏览器中,以及正在查看同一页面的任何其他连接的浏览器。

【讨论】:

    【解决方案4】:

    我意识到这篇文章已经有好几年了,但有时像我这样经过认证的新手需要一个完全精简为绝对最简单形式的工作示例。

    我能找到的每个简单的 socket.io 示例都涉及 http.createServer()。但是,如果您想在现有网页中包含一些 socket.io 魔法怎么办?这是我能想到的最简单和最小的例子。

    这只是返回一个从控制台传递过来的大写字符串。

    app.js

    var http = require('http');
    
    var app = http.createServer(function(req, res) {
            console.log('createServer');
    });
    app.listen(3000);
    
    var io = require('socket.io').listen(app);
    
    
    io.on('connection', function(socket) {
        io.emit('Server 2 Client Message', 'Welcome!' );
    
        socket.on('Client 2 Server Message', function(message)      {
            console.log(message);
            io.emit('Server 2 Client Message', message.toUpperCase() );     //upcase it
        });
    
    });
    

    index.html:

    <!doctype html>
    <html>
        <head>
            <script type='text/javascript' src='http://localhost:3000/socket.io/socket.io.js'></script>
            <script type='text/javascript'>
                    var socket = io.connect(':3000');
                     // optionally use io('http://localhost:3000');
                     // but make *SURE* it matches the jScript src
                    socket.on ('Server 2 Client Message',
                         function(messageFromServer)       {
                            console.log ('server said: ' + messageFromServer);
                         });
    
            </script>
        </head>
        <body>
            <h5>Worlds smallest Socket.io example to uppercase strings</h5>
            <p>
            <a href='#' onClick="javascript:socket.emit('Client 2 Server Message', 'return UPPERCASED in the console');">return UPPERCASED in the console</a>
                    <br />
                    socket.emit('Client 2 Server Message', 'try cut/paste this command in your console!');
            </p>
        </body>
    </html>
    

    运行:

    npm init;  // accept defaults
    npm  install  socket.io  http  --save ;
    node app.js  &
    

    使用类似port test 的东西来确保您的端口是开放的。

    现在浏览到http://localhost/index.html 并使用浏览器控制台将消息发送回服务器。

    最好的猜测是,当使用 http.createServer 时,它会为您更改以下两行:

    <script type='text/javascript' src='/socket.io/socket.io.js'></script>
    var socket = io();
    

    我希望这个非常简单的例子能让我的新手伙伴们免于苦恼。请注意,我没有使用“保留字”来查找用户定义的变量名称来进行套接字定义。

    【讨论】:

    • every simple socket.io example i could find involved http.createServer(). but what if you want to include a bit of socket.io magic in an existing webpage mhm yes ... var app = http.createServer( - wut
    • 非常非常有用,你拯救了我的一天。非常感谢。这是最简单的答案,无需在 node.js 中加载太多,此示例更适合所有初学者开始并熟悉 node。再次感谢您
    【解决方案5】:

    index.html

    <!doctype html>
    <html>
      <head>
        <title>Socket.IO chat</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; }
          #messages { margin-bottom: 40px }
        </style>
      </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="https://code.jquery.com/jquery-1.11.1.js"></script>
        <script>
          $(function () {
            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));
              window.scrollTo(0, document.body.scrollHeight);
            });
          });
        </script>
      </body>
    </html>
    

    index.js

    var app = require('express')();
    var http = require('http').Server(app);
    var io = require('socket.io')(http);
    var port = process.env.PORT || 3000;
    
    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(port, function(){
      console.log('listening on *:' + port);
    });
    

    并运行这些命令以运行应用程序。

    npm init;  // accept defaults
    npm  install  socket.io  http  --save ;
    node start
    

    并打开网址:- http://127.0.0.1:3000/ 端口可能不同。 你会看到这个输出

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-11
      • 2010-11-02
      • 1970-01-01
      • 1970-01-01
      • 2019-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多