2014年12月8日 星期一

socket.io 應用

Socket.io 應用很像ajax, firebase, 這次測試的是網頁和backend的溝通
安裝 npm install socket.io
你可以參考官方的 demo: http://socket.io/ by (http://automattic.com/)

首先需要啟動server backend:
var http = require('http');
var url = require('url');
var fs = require('fs');
var path = require('path');
var io = require('socket.io')(server);
var readline = require('readline');

var server = http.createServer(function(req,res){
 var urls = url.parse(req.url);
 var relpath = path.join(__dirname,'/www/',urls.pathname);

 fs.stat(relpath,function(err,stats){
  if(err){
   res.writeHead(404,{});
   res.end();
  }else{
   if(stats.isDirectory()){
    //is Directory
    fs.readFile(relpath+'/index.html',function(err,data){
     console.log('View index');
     if(err){
      res.writeHead(404);
      res.end();
     }else{
      res.writeHead(200,{'Content-Type':'text/html'});
      res.end(data);
     }
    });
   }else{
    fs.readFile(relpath,function(err,data){
     if(err){
      res.writeHead(404);
      res.end();
     }else{
      res.writeHead(200,{'Content-Type':'text/html'});
      res.end(data); 
     }
    });
   }
  }
 });
});
var rl = readline.createInterface({
 input:process.stdin,
 output: process.stdout
});
io.on('connection', function(socket){
 console.log('connectioned!');
  
  process.stdout.write("KeyWord: ");
  rl.on('line',function(cmd){
   io.emit(cmd);
  });

  socket.on('event', function(data){
   console.log('Get Event!');
   console.log(data);
  });

  socket.on('disconnect', function(){});
});

server.listen(80);
io.listen(server);

上面寫的 io.on 就是和 front 前端溝通了,接下來前端需要接受資料,用javascript, 也要匯入library:
<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <title>Hello World</title>
 <script type="text/javascript" src="./socket.io/socket.io.js" ></script>
 <script>
  var socket = io('http://localhost');
  socket.on('connect',function(){
   console.log("Hello World");
   socket.emit('event',15);
  });
  socket.on('event',function(data){
   console.log(data);
  });
  socket.on('disconnect',function(){});
 </script>
</head>
<body>
Hello World
</body>
</html>

整個專案: https://github.com/hpcslag/socket.io

沒有留言:

張貼留言

© Mac Taylor, 歡迎自由轉貼。
Background Email Pattern by Toby Elliott
Since 2014