Nodejs SOCKET.IO.JS 的使用
Nodejs SOCKET.IO.JS 的使用
How to use Installing
npm install socket.io
Using with Node HTTP server
For this example, simply run npm install socket.io
Server (app.js)
var app = require(‘http’).createServer(handler) , io = require(‘socket.io’).listen(app) , 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.sockets.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 3 web framework
Express 3 requires that you instantiate a http.Server
to attach socket.io to first:
Server (app.js)
var app = require(‘express’)() , server = require(‘http’).createServer(app) , io = require(‘socket.io’).listen(server);
server.listen(80);
app.get(’/’, function (req, res) { res.sendfile(__dirname + ‘/index.html’); });
io.sockets.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 web framework
You can serve normal pages and AJAX requests with Express, and attach your socket.io server
For this example, simply run npm install socket.io express
Server (app.js)
var app = require(‘express’).createServer() , io = require(‘socket.io’).listen(app);
app.listen(80);
app.get(’/’, function (req, res) { res.sendfile(__dirname + ‘/index.html’); });
io.sockets.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:
Server
// note, io.listen(<port>) will create a http server for you var io = require(‘socket.io’).listen(80);
io.sockets.on(‘connection’, function (socket) { io.sockets.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.sockets.emit(‘user disconnected’); }); });
Storing data associated to a client
Sometimes it’s necessary to store data associated with a client that’s necessary for the duration of the session. Server
var io = require(‘socket.io’).listen(80);
io.sockets.on(‘connection’, function (socket) { socket.on(‘set nickname’, function (name) { socket.set(‘nickname’, name, function () { socket.emit(‘ready’); }); });
socket.on(‘msg’, function () { socket.get(‘nickname’, function (err, name) { console.log('Chat message by ', name); }); }); });
Client
<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>
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.
This has the benefit of multiplexing
a single connection. Instead of socket.io using two WebSocket
connections, it’ll use one.
Server
var io = require(‘socket.io’).listen(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
<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
.
If a certain client is not ready to receive messages (because of network slowness or other issues, or because he’s connected through long polling and is in the middle of a request-response cycle), if he 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’).listen(80);
io.sockets.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:
Server
var io = require(‘socket.io’).listen(80);
io.sockets.on(‘connection’, function (socket) { socket.on(‘ferret’, function (name, fn) { fn(‘woot’); }); });
Client
<script>
var socket = io.connect(); // TIP: .connect 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’).listen(80);
io.sockets.on(‘connection’, function (socket) { socket.broadcast.emit(‘user connected’); });
Using it just as a cross-browser WebSocket.
If you just want the WebSocket semantics, you can do that too. Simply leverage send
and listen on the message
event:
Server
var io = require(‘socket.io’).listen(80);
io.sockets.on(‘connection’, function (socket) { socket.on(‘message’, function () { }); socket.on(‘disconnect’, function () { }); });
Client
<script> var socket = io.connect(‘http://localhost/’); socket.on(‘connect’, function () { socket.send(‘hi’);
socket.on('message', function (msg) {
// my msg
});
}); </script>
Nodejs SOCKET.IO.JS 的使用
安装
首先需要安装 socket.io
库。可以使用以下命令:
npm install socket.io
使用 Node.js HTTP 服务器
服务器端代码 (app.js)
var http = require('http').createServer(handler),
io = require('socket.io')(http),
fs = require('fs');
http.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);
});
});
客户端代码 (index.html)
<!DOCTYPE html>
<html>
<head>
<title>Socket.IO Example</title>
</head>
<body>
<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>
</body>
</html>
使用 Express 框架
服务器端代码 (app.js)
var express = require('express'),
http = require('http').createServer(app),
io = require('socket.io')(http);
http.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);
});
});
客户端代码 (index.html)
<!DOCTYPE html>
<html>
<head>
<title>Socket.IO Example</title>
</head>
<body>
<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>
</body>
</html>
发送和接收事件
socket.io
允许你发送和接收自定义事件。
服务器端代码
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
io.sockets.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.sockets.emit('user disconnected');
});
});
存储与客户端关联的数据
有时你需要存储与客户端关联的数据。
服务器端代码
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.on('set nickname', function (name) {
socket.set('nickname', name, function () {
socket.emit('ready');
});
});
socket.on('msg', function () {
socket.get('nickname', function (err, name) {
console.log('Chat message by ', name);
});
});
});
命名空间
如果你的应用程序需要多个不同的命名空间,可以使用 namespace
。
服务器端代码
var io = require('socket.io').listen(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' });
});
客户端代码
<!DOCTYPE html>
<html>
<head>
<title>Socket.IO Namespace Example</title>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<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>
</body>
</html>
以上是 socket.io
在 Node.js 中的基本使用方法,涵盖了安装、服务器和客户端代码的编写、事件处理、数据存储以及命名空间的使用。
You are trying to attach socket.io to an express request handler function. Please pass a http.Server instance. socket.io需要http模块
var http = require('http');
var express = require("express");
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(80);
Node.js & Socket.IO 使用示例
安装
首先安装 socket.io
:
npm install socket.io
使用 Node HTTP Server
服务器端 (app.js)
var http = require('http');
var fs = require('fs');
var io = require('socket.io')(http.createServer().listen(80));
http.createServer(function (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);
});
}).listen(80);
io.on('connection', function(socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function(data) {
console.log(data);
});
});
客户端 (index.html)
<!DOCTYPE html>
<html>
<head>
<title>Socket.IO Example</title>
</head>
<body>
<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>
</body>
</html>
使用 Express 框架
服务器端 (app.js)
var express = require('express');
var http = require('http');
var io = require('socket.io');
var app = express();
var server = http.createServer(app);
var socket = io.listen(server);
server.listen(80);
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
socket.sockets.on('connection', function(socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function(data) {
console.log(data);
});
});
客户端 (index.html)
<!DOCTYPE html>
<html>
<head>
<title>Socket.IO Example with Express</title>
</head>
<body>
<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>
</body>
</html>
以上是使用 Node.js 和 Socket.IO 进行基本连接和消息传递的示例。你可以根据需要扩展功能,如广播消息、处理事件、存储用户数据等。