Socket.IO 中文文档 概述部分

原文站点:Socket.IO

概述OVERVIEW

使用方法How to use

安装Installing

$ npm install socket.io --save

使用NODE.JS服务器Using with Node http server

Server (app.js)
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');

app.listen(80);

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' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});
Client (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>

使用EXPRESS.JS(3.-/4.-)框架Using with Express 3/4

服务器端(/app.js)Server (app.js)

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

server.listen(80);

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

客户端(/public/javascript/chat.js & /views/index.html)Client (index.html)

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

使用更早的EXPRESS框架Using with the Express framework

Server (app.js)

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

app.listen(80);

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

客户端Client (index.html)

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

收发定制事件Sending and receiving events

Socket.IO 提供了从服务器发布和接受定制事件的途径。不仅仅能够完成连接、发信、断开连接这样一般事件的收发,开发人员可以发布如下例所示的定制事件。
Socket.IO allows you to emit and receive custom events. Besides connect, message and disconnect, you can emit custom events:

服务端Server

//注意,io(<port>) 将会为您的应用创建一个http服务进程。
//note, io(<port>) will create a http server for you

var io = require('socket.io')(80);

io.on('connection', function (socket) {
  io.emit('this', { will: 'be received by everyone'});

  socket.on('private message', function (from, msg) {
    console.log('I received a private message by ', from, ' saying ', msg);
  });

  socket.on('disconnect', function () {
    io.emit('user disconnected');
  });
});

将事件限制在命名空间内Restricting yourself to a namespace

如果你希望在一个特定的web应用中控制多个消息与事件的收发,推荐使用切换方式(默认/其他命名空间)来实现。如果你希望调用第三方的代码,或者编写一些希望与他人共享的代码,socket.io提供了一种途径:规定socket的命名空间。这有助于创建多线连接:实现了不去创建两个websocket连接,而是使用一个连接完成多线操作。
If you have control over all the messages and events emitted for a particular application, using the default / namespace works. If you want to leverage 3rd-party code, or produce code to share with others, socket.io provides a way of namespacing a socket.
This has the benefit of multiplexing a single connection. Instead of socket.io using two WebSocket connections, it’ll use one.

服务端Server (app.js)

var io = require('socket.io')(80);
var chat = io
  .of('/chat')//!of(namespace)确定了这个连接所在的命名空间
  .on('connection', function (socket) {
    socket.emit('a message', {
        that: 'only'
      , '/chat': 'will get'
    });
    chat.emit('a message', {
        everyone: 'in'
      , '/chat': 'will get'
    });
  });

var news = io
  .of('/news')//!of(namespace)确定了这个连接所在的命名空间
  .on('connection', function (socket) {
    socket.emit('item', { news: 'item' });
  });

客户端Client (index.html)

<script>
  var chat = io.connect('http://localhost/chat')//!选择命名空间接受/发送特定的信息。
    , news = io.connect('http://localhost/news');//!选择命名空间接受/发送特定的信息。

  chat.on('connect', function () {
    chat.emit('hi!');
  });

  news.on('news', function () {
    news.emit('woot');
  });
  </script>

发送易变信息Sending volatile messages

有时候,某些消息的获取不是非常必要,甚至可以被抛弃。假想你有一个实时显示比伯这个关键词的所有推特的应用,如果某个客户端并没有准备好接受信息(因为网速慢或其他原因,又或者因为这些客户端正尝试通过长轮询的方式并且恰恰处在请求回应的过程之中)。如果这一次他们不能够完完全全地接收到比伯的实时推特不会影响这个应用的正常使用,在这种情况下,你就会希望将那些推特的信息当作易变信息(volatile messages)来发送。
Sometimes certain messages can be dropped. Let’s say you have an app that shows realtime tweets for the keyword bieber.
If a certain client is not ready to receive messages (because of network slowness or other issues, or because they’re connected through long polling and is in the middle of a request-response cycle), if they doesn’t receive ALL the tweets related to bieber your application won’t suffer.
In that case, you might want to send those messages as volatile messages.

服务端Server

var io = require('socket.io')(80);

io.on('connection', function (socket) {
  var tweets = setInterval(function () {
    getBieberTweet(function (tweet) {
      socket.volatile.emit('bieber tweet', tweet);//soket.volatile.emit就是这样的方式。
    });
  }, 100);

  socket.on('disconnect', function () {
    clearInterval(tweets);
  });
});

发送并获得返回数据Sending and getting data (acknowledgements)

有些时候,你可能希望得到客户端已经接收到信息的状态响应。
为了实现这样的期望,十分简单,只需要在.send或.emit函数的最后一个参量传递一个函数。不仅如此,当你使用.emit函数时,确认信息是你所指定的,意味着你还可以传递确认信息的内容。
Sometimes, you might want to get a callback when the client confirmed the message reception.
To do this, simply pass a function as the last parameter of .send or .emit. What’s more, when you use .emit, the acknowledgement is done by you, which means you can also pass data along:

服务端Server (app.js)

var io = require('socket.io')(80);

io.on('connection', function (socket) {
  socket.on('ferret', function (name, fn) {//传递一个fn函数
    fn('woot');//指定用于响应的确认信息
  });
});

客户端Client (index.html)

<script>
  var socket = io(); 
  // 小贴士:没有任何的参量的io()会进行自动检查。
  //TIP: io() with no args does auto-discovery
  socket.on('connect', function () { 
  //小贴士:你可以监听connect事件,而是直接监听ferret事件。
  // TIP: you can avoid listening on `connect` and listen on events directly too!
    socket.emit('ferret', 'tobi', function (data) {
      console.log(data); // data will be 'woot'
    });
  });
</script>

广播消息Broadcasting messages

想要广播一则消息,只需要添加一个broadcast标记给emit或send方法。广播意味着把消息发送给除了消息发送者以外的所有客户端。
To broadcast, simply add a broadcast flag to emit and send method calls. Broadcasting means sending a message to everyone else except for the socket that starts it.

服务端Server

var io = require('socket.io')(80);

io.on('connection', function (socket) {
  socket.broadcast.emit('user connected');
});

当作跨浏览器websocket使用Using it just as a cross-browser WebSocket

如果你只是希望使用websocket的语义,你也可以做到。只需要在消息的事件里调用send和listen方法。
If you just want the WebSocket semantics, you can do that too. Simply leverage send and listen on the messageevent:

服务端Server (app.js)

var io = require('socket.io')(80);

io.on('connection', function (socket) {
  socket.on('message', function () { });
  socket.on('disconnect', function () { });
});

客户端Client (index.html)

<script>
  var socket = io('http://localhost/');
  socket.on('connect', function () {
    socket.send('hi');

    socket.on('message', function (msg) {
      // my msg
    });
  });
</script>

如果你并不在意诸如重连这样的逻辑,你可以查看一下Engine.IO,它是Socket.IO所使用的WebSocket语义传输层框架。
If you don’t care about reconnection logic and such, take a look at Engine.IO, which is the WebSocket semantics transport layer Socket.IO uses.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值