cnhome的专栏

浪淘沙

Socket.IO 简介

官方站点:http://socket.io/
 
 

socket.io(官网:http://socket.io/)是一个跨平台,多种连接方式自动切换,做即时通讯方面的开发很方便,而且能和expressjs提供的传统请求方式很好的结合,即可以在同一个域名,同一个端口提供两种连接方式:request/response, websocket(flashsocket,ajax…).
下面是网摘的一个简单的聊天室代码。

server.js:

var express =  require('express'),
    app = express.createServer(),
    io = require('socket.io').listen(app),
    fs = require('fs'),
    mime = require('mime');

app.listen(8001);
app.get('/',function(req,res){
    var realpath = __dirname + '/client.html';
    //console.log(realpath);
    res.writeHead(200,{'Content-Type':mime.lookup(realpath)});
    res.end(fs.readFileSync(realpath));
});
app.get('/jquery.min.js',function(req,res){
    var realpath = __dirname + '/jquery.min.js';
    //console.log(realpath);
    res.writeHead(200,{'Content-Type':mime.lookup(realpath)});
    res.end(fs.readFileSync(realpath));
});
var getCurrTime = function(){
    var d  = new Date();
    return d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate()+' '+d.getHours()+':'+d.getMinutes()+':'+d.getSeconds();
};
io.sockets.on('connection', function (socket) {
  socket.on('msg', function(msg){
     var data = {username:socket.name,time:getCurrTime(),msg:msg};
     socket.emit('msg',data);
     socket.broadcast.emit('msg',data);
  });
  socket.on('login', function(username){
     socket.name = username;
     var data = {username:'SYSTEM',time:getCurrTime(),msg:'welcome '+socket.name+' in...'};
     socket.broadcast.emit('msg',data);
     socket.emit('msg',data);
  });
  socket.on('logout', function(username){
     var data = {username:'SYSTEM',time:getCurrTime(),msg:'bye, '+socket.name+' leave...'};
     socket.broadcast.emit('msg',data);
     socket.emit('msg',data);
  });
  socket.on('disconnect', function () {
        socket.send(getCurrTime()+' '+socket.name+ " out...");
  });
});

client.html:
<script type="text/javascript" src="/jquery.min.js"></script>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script>
var url = window.location.protocol+'//'+window.location.host;
//alert(url);
var socket = io.connect(url);
socket.on('msg', function (data) {
showMsg(data);
});
var showMsg = function (data){};
$(function(){
showMsg = function(data){
var time = $('<span style="color:red;"></span>').html(data.time+'&nbsp;&nbsp;');
var username = $('<span style="color:blue;"></span>').html(data.username+'&nbsp;&nbsp;');
var say = $('<span style="color:black;"></span>').html('say:&nbsp;&nbsp;');
var msg = $('<span style="color:green;"></span>').text(data.msg);
var div = $('<div style="display:none;"></div>').append(time).append(username).append(say).append(msg);
div.insertAfter('#demo span:eq(0)').slideDown();//fadeIn();
//div.appendTo('#demo').fadeIn();
};
$('#butt_login').click(function(){
socket.emit('login',$('#username').val());
});
$('#butt_logout').click(function(){
socket.emit('logout',$('#username').val());
});
$('#butt_send').click(function(){
socket.emit('msg',$('#message').val());
});
});

</script>
Name: <input type="text" id='username' value=""/>
<input type="button" value="join" id="butt_login"/>
<input type="button" value="leave" id="butt_logout"/>
<br>
message: <input type="text" id='message' value=""/>
<input type="button" value="send" id="butt_send"/>
<div id='demo' style="boder:1px;border-style:dotted;width:800px;height:300px;overflow:auto;">
<span>...</span>
</div> 
Tips:
1.确认tmp/foo/路径下已有jquery.min.js,如果没有,需要创建一个该文件;
2.确认已安装mime,安装方法:# npm install mime;
3.由于socket.io.js文件中会要求flash player版本》10.0;请确保此项要求满足。
Demo运行方法:# node server.js     开启浏览器输入localhost:8001(端口号可在server.js里配置),即可看到运行效果。
 
-------------------------------------------------------------------------------------------------
 
使用方面可以参考:http://socket.io/#how-to-use 说到底还是使用的node.js的技术,不了解的可以参考下边的文章:
 
 
 
 
What is Socket.IO?

Socket.IO aims to make realtime apps possible in every          browser and mobile device, blurring the differences between the different          transport mechanisms. It's care-free realtime 100% in JavaScript.

Server

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

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

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>
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cnhome/article/details/6883035
个人分类: Java编程
想对作者说点什么? 我来说一句

socket.io应用简介

2015年07月12日 2.72MB 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭