原文链接:http://cnodejs.org/topic/50a1fcc7637ffa4155b5a264
我自己在用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')0405 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');
}else{
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三个事件外,用户可以自定义自己的事件
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'});}); 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.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 <scriptsrc="/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 +" "+ 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>
<textareaid="all"cols=40rows=20>
</textarea><br/>
<label>Message:</label>
<inputid="message"type="text"name="message"cols=120/>
<inputid="chat_btn"type="button"value="chat"onclick="javascript:chat_fn()"/>
<label>NickName:</label>
<inputid="nickname"typee="text"name="nickname"/>
<inputid="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);});});});