socket.io实现在线群聊功能
我自己在用socket.io开发,对官方网站上的文档,进行简单的整理,然后自己写了一个简单的聊天程序。最最开始
先安装socket.io:
npm install socket.io
利用Node的搭建Http服务
分为两个文件,服务端文件app.js和客户端index.html
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);}); });
这里需要注意的是: require(‘socket.io').listen(app) 实际上这句就是讲socket的监听加入的app设置的http模块了 io.sockets.on('connection',function()…)这里设置了在连接后进行的处理,代码示例中,主要包含两件事,一个是向前段发送news的事件,一个是监听my other event事件。
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>
客户端一个引用了socket.io.js的javscript库还有就是连接服务器(通过io.connect(‘http://localhost')) 之后在监听收到news的事件后,发送my other event事件
利用Express3框架上面的例子只是使用nodejs建立了一个交互,也可以使用express2的web框架, 具体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); });});
接收发送事件 socket.io允许用户自定义发送接收的事件。除了connect,message,disconnect三个事件外,用户可以自定义自己的事件
// note, io.listen(<port>) will create a http server for youvar 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'); });});
存储数据有的时候需要存储一些和客户端关联的数据在会话里,socket.io也是支持的,代码如下:
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); }); });});
socket.set和socket.get方法分为用于设置和获取变量。
设置命名空间有的时候要一个程序支持多个应用,如果使用默认的 “/” 命名空间可能会比较混乱。如果想让一个连接可以支持多个连接,可以使用如下的命名空间的方法:
app.js
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' }); });
client.js
<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>
发送获取数据有的时候,你需要在发送数据后,等待服务器的消息确认。当然简单的发,可以通过两次消息发送,来完成。这里介绍一种使用回调函数的方法:
app.js
var io = require('socket.io').listen(80); io.sockets.on('connection', function (socket) { socket.on('ferret', function (name, fn) { fn('woot'); });}); client.html <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>
广播向所有的连接触发事件,这里注意:不包括本身连接的事件。
var io = require('socket.io').listen(80); io.sockets.on('connection', function (socket) { socket.broadcast.emit('user connected');});
我写的聊天程序:
index.html
<script src="/socket.io/socket.io.js"></script><script> var socket = io.connect('http://localhost'); socket.on("notice", function(data){ var msg = document.getElementById('all').value; document.getElementById('all').innerText = msg + "\n" + data.message; }); var chat_fn = function(){ var msg = document.getElementById("message").value; socket.emit("chat", {message: msg}); }; socket.on("nickname ready", function(data){ alert("nickname changed."); }); var change_nickname = function(){ var nickname = document.getElementById("nickname").value; socket.emit('set nickname', nickname); };</script><textarea id="all" cols=40 rows=20></textarea><br /><label>Message:</label><input id="message" type="text" name="message" cols=120/><input id="chat_btn" type="button" value="chat" onclick="javascript:chat_fn()" /><label>NickName:</label><input id="nickname" typee="text" name="nickname" /><input id="chang_name" type="button" value="nickname" onclick="javascript:change_nickname()" /> 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); // }); socket.set('nickname', 'nickname', function(){ }); socket.on('set nickname', function(name){ socket.set('nickname', name, function(){ console.log("change nickname=>" + name); socket.emit('nickname ready'); }); }); socket.on('chat', function(data){ socket.get('nickname', function(err, name){ socket.emit("notice", {message: name + ":" + data.message}); socket.broadcast.emit("notice", {message: name + ":" + data.message}); console.log("chat: " + data.message); }); });});