Skip to main content

Realtime Chat - Part I

Dev
Table of Contents
Realtime Chat - This article is part of a series.
Part 1: This Article

这篇文章就介绍一下架个 socket.io 服务器

基本要求
#

安装 Socket.IO
#

npm install socket.io

使用 Socket.IO
#

服务器:app.js

var app = require("http").createServer(handler);
var io = require("socket.io")(app);
var fs = require("fs");

app.listen(3000);

function handler(req, res) {
  fs.readFile(__dirname + "/index.html", function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end("Error loading index.html");
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.on("connection", function (socket) {
  // 推一个事件到客户端 (游览器)
  socket.emit("news", { hello: "world" });

  // 接收到一个来自客户端独特事件: `my other event`
  socket.on("my other event", function (data) {
    console.log(data); // 简单的在后台看看而已
  });
});

客户端:index.html

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io("http://localhost");
  socket.on("news", function (data) {
    console.log(data);
    socket.emit("my other event", { my: "data" });
  });
</script>

运行 Node 服务器
#

node app.js

游览器就打开 http://localhost:3000

扩展阅读
#

  1. 如何使用 Nginx 反代理就看 这里
  2. Socket.IO 官方文件
Realtime Chat - This article is part of a series.
Part 1: This Article