您的位置:首页 > 其它

socket.io的安装和使用

2015-10-24 15:56 316 查看
安装socket.io

(有资料说需要先安装python2.7以上,VS2008以上才能安装成功,但官网上没有这方面提示)

$ npm install socket.io

Using with Node http server(使用HTTP服务器节点)

Server (app.js)

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

app.listen(90);

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="http://localhost:90/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost:90');//var socket = io("ws://localhost:90");
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>


Using with Express 3/4(使用Express)

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);
});
});


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>


Using with the Express framework(使用Express 框架)

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 allows you to emit and receive custom events. Besides
connect, message and
disconnect, you can emit custom events:(socket.io可以发射和接收自定义事件。除了connect,message和disconnect,您可以发出自定义事件:)

Server

// 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(限制自己的命名空间)

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.(如果您已经控制了特定应用程序发出的所有消息和事件,使用默认/命名空间工程。如果你想利用第三方代码生成代码,或与他人分享,socket.io提供一种命名空间插座。)

This has the benefit of multiplexing a single connection. Instead of socket.io using two
WebSocket connections, it’ll use one.

(这有利于多路复用。而不是使用两个WebSocket连接socket.io,它会使用一个。)

Server (app.js)

var io = require('socket.io')(80);
var chat = io
.of('/chat')
.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')
.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(发送不稳定消息)

Sometimes certain messages can be dropped. Let’s say you have an app that shows realtime tweets for the keyword
bieber.

有时某些消息可以被删除。让我们说你有一个应用程序,显示实时鸣叫的关键字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);
});
}, 100);

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


Sending and getting data (acknowledgements)(发送和获取数据(确认收到))

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:

要做到这一点,只需要传递函数作为最后一个参数.send 或者 .emit。更甚的是,当你使用.emit时,你会发出确认,这意味着你也可以将数据传递:

Server (app.js)

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

io.on('connection', function (socket) {
socket.on('ferret', function (name, fn) {
fn('woot');
});
});


Client (index.html)

<script>
var socket = io(); // TIP: io() with no args does auto-discovery
socket.on('connect', function () { // 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(广播消息)

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');
});


Using it just as a cross-browser WebSocket(使用它只是作为一个跨浏览器的WebSocket)

If you just want the WebSocket semantics, you can do that too. Simply leverage
send and listen on the message event:

如果你只是想WebSocket语义,你也可以这样做。简单地利用发送和听消息事件:

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>


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.

如果你不在乎重逻辑等,采取在engine.io一看,这是socket.io使用WebSocket语义传输层。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: