首页 > 代码库 > socket.io实现在线群聊

socket.io实现在线群聊

我自己在用socket.io开发,对官方网站上的文档,进行简单的整理,然后自己写了一个简单的聊天程序。最最开始

先安装socket.io:

1 npm install socket.io

利用Node的搭建Http服务

分为两个文件,服务端文件app.js和客户端index.html

app.js01 var app = require(‘http‘).createServer(handler)02   , io = require(‘socket.io‘).listen(app)03   , fs = require(‘fs‘)04 05 app.listen(80);06 07 function handler (req, res) {08   fs.readFile(__dirname + ‘/index.html‘,09   function (err, data) {10     if (err) {11       res.writeHead(500);12       return res.end(‘Error loading index.html‘);13     }14 15     res.writeHead(200);16     res.end(data);17   });18 }19 20 io.sockets.on(‘connection‘, function (socket) {21   socket.emit(‘news‘, { hello: ‘world‘ });22   socket.on(‘my other event‘, function (data) {23     console.log(data);24   });25 });

这里需要注意的是: require(‘socket.io’).listen(app) 实际上这句就是讲socket的监听加入的app设置的http模块了 io.sockets.on(‘connection’,function()…)这里设置了在连接后进行的处理,代码示例中,主要包含两件事,一个是向前段发送news的事件,一个是监听my other event事件。

index.html1 <script src="/socket.io/socket.io.js"></script>2 <script>3   var socket = io.connect(‘http://localhost‘);4   socket.on(‘news‘, function (data) {5     console.log(data);6     socket.emit(‘my other event‘, { my: ‘data‘ });7   });8 </script>

客户端一个引用了socket.io.js的javscript库还有就是连接服务器(通过io.connect(‘http://localhost’)) 之后在监听收到news的事件后,发送my other event事件

利用Express3框架上面的例子只是使用nodejs建立了一个交互,也可以使用express2的web框架, 具体app.js代码如下:

v

ar 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.jsvar 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.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.jsvar 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);    });  });});

socket.io实现在线群聊