带套接字消息的 Hello 世界

安装节点模块

npm install express
npm install socket.io

Node.js 服务器

const express = require('express'); 
const app = express();
const server = app.listen(3000,console.log("Socket.io Hello Wolrd server started!"));
const io = require('socket.io')(server);

io.on('connection', (socket) => {
    //console.log("Client connected!");
    socket.on('message-from-client-to-server', (msg) => {
        console.log(msg);
    })
    socket.emit('message-from-server-to-client', 'Hello World!');
});

浏览器客户端

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Hello World with Socket.io</title>
  </head>
  <body>
    <script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
    <script>
      var socket = io("http://localhost:3000");
      socket.on("message-from-server-to-client", function(msg) {
          document.getElementById('message').innerHTML = msg;
      });
      socket.emit('message-from-client-to-server', 'Hello World!');
    </script>
    <p>Socker.io Hello World client started!</p>
    <p id="message"></p>
  </body>
</html>

在上面的示例中,socket.io 库的路径定义为/socket.io/socket.io.js

即使我们没有编写任何代码来为 socket.io 库提供服务,Socket.io 也会自动执行此操作。