轉載:socket.io 入門

原文連接:http://cnodejs.org/topic/50a1fcc7637ffa4155b5a264javascript

我本身在用socket.io開發,對官方網站上的文檔,進行簡單的整理,而後本身寫了一個簡單的聊天程序。
最最開始html

先安裝socket.io:java

npm install socket.io

 

利用Node的搭建Http服務node

分爲兩個文件,服務端文件app.js和客戶端index.htmlweb

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事件。express

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事件npm

利用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

 
 
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 +"\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>
<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);});});});
相關文章
相關標籤/搜索