HTML5 Web socket和socket.io

what is websockets


 

Two-way communication over ont TCP socket, a type of PUSH technology

   HTML5的新特性,用于双向推送消息(例如网页聊天,手机推送消息等)

 

  原理:

  1. client利用regular http请求webpage
  2. 请求的webpage 执行javascript脚本,open a connection to server.
  3. 有新的信息时服务器和客户端可以相互发送信息(Real-time traffic from the server to the client and from the client to the server

  HTML5 WebSockets

 

客户端


 

  说明:

  readyState:

CONNECTING (0):表示还没建立连接;
OPEN (1): 已经建立连接,可以进行通讯;
CLOSING (2):通过关闭握手,正在关闭连接;
CLOSED (3):连接已经关闭或无法打开;

  

  url: WebSocket 服务器的网络地址,协议通常是”ws”或“wss(加密通信)”,

  事件:

  • send:向服务器端发送数据
  • close 方法就是关闭连接;
  • onopen连接建立,即握手成功触发的事件;
  • onmessage收到服务器消息时触发的事件;
  • onerror异常触发的事件;

 

  使用例子:

// 创建一个Socket实例
var socket = new WebSocket('ws://localhost:8080'); 

// 打开Socket 
socket.onopen = function(event) { 

  // 发送一个初始化消息
  socket.send('I am the client and I\'m listening!'); 

  // 监听消息
  socket.onmessage = function(event) { 
    console.log('Client received a message',event); 
  }; 

  // 监听Socket的关闭
  socket.onclose = function(event) { 
    console.log('Client notified socket has closed',event); 
  }; 

  // 关闭Socket.... 
  //socket.close() 
};

 

服务器端


 

 jWebSocket (Java)
 web-socket-ruby (ruby)
 Socket IO-node (node.js)

 

 下面以socket.io说明,环境说明:(node.js安装见 http://www.cnblogs.com/wishyouhappy/p/3647037.html

 1. 安装socket.io

 npm install -g socket.io

  2.使用require引入http和socket.io

var http = require("http");
var io= require('socket.io'); 

  3.创建server

var server = http.createServer(function(request, response){
    response.writeHead(200,{"Content-Type":"text/html"});
    response.write("WebSocket Start~~~~~~~~~~~~");
    response.end("");
}).listen(8000);

 4.监听

var socket= io.listen(server); 

 5.例子:

var http = require("http");
var io= require('socket.io'); 
var server = http.createServer(function(request, response){
    response.writeHead(200,{"Content-Type":"text/html"});
    response.write("WebSocket Start~~~~~~~~~~~~");
    response.end("");
}).listen(8000);

var socket= io.listen(server); 

// 添加一个连接监听器
socket.on('connection', function(client){ 

  client.on('message',function(event){ 
    console.log('Received message from client!',event); 
  }); 
  client.on('disconnect',function(){ 
    clearInterval(interval); 
    console.log('Server has disconnected'); 
  }); 
});

 

数据发送两种方式send和emit


 

使用send和emit都可以发送数据,但是emit可以自定义事件,如下:

emit:

//服务器

socket.on('connection', function(client){ 
  client.on('message',function(event){ 
    client.emit('emitMessage', { hello: 'messgge received, wish you happy'+new Date().toString() });
  }); 
 
});


//客户端
socket.on('emitMessage',function(data) { 
  document.getElementById("result").innerHTML+=data.hello + "<br />";
 
});

send:

//服务器

socket.on('connection', function(client){ 
  client.send('hello, I am the server');
});


//客户端
socket.on('message',function(data) { 
  document.getElementById("result").innerHTML+=data + "<br />";
 
});

 

实例:(socket.io)


 

客户端:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
div{
    border-radius: 10px;
    border: 2px solid pink;
    width:800px;
}
</style>
</head>
<body>
<h1></h1>
<div id="result"></div>
<script src="http://localhost:8000/socket.io/socket.io.js"></script>
<script>
//创建Socket.IO实例,建立连接

var socket = io.connect('http://localhost:8000');

// 添加一个连接监听器
socket.on('connect',function() { 
  console.log('Client has connected to the server!'); 
});

// 添加一个连接监听器
socket.on('message',function(data) { 
  document.getElementById("result").innerHTML+=data + "<br />";
 
});
socket.on('emitMessage',function(data) { 
  document.getElementById("result").innerHTML+=data.hello + "<br />";
 
});

// 添加一个关闭连接的监听器
socket.on('disconnect',function() { 
  console.log('The client has disconnected!'); 
}); 

// 通过Socket发送一条消息到服务器
function sendMessageToServer(message) { 
  socket.send(message); 
}
var date = new Date();
var ms="Time: "+date.toString()+"Today is a nice day, wish you happy";
setInterval("sendMessageToServer(ms)",1000);
</script>

</body>
</html>

服务器:

var http = require("http");
var io= require('socket.io'); 
var server = http.createServer(function(request, response){
    response.writeHead(200,{"Content-Type":"text/html"});
    response.write("WebSocket Start~~~~~~~~~~~~");
    response.end("");
}).listen(8000);

var socket= io.listen(server); 

// 添加一个连接监听器
socket.on('connection', function(client){ 

  client.on('message',function(event){ 
    console.log('Received message from client!',event); 
    client.emit('emitMessage', { hello: 'messgge received, wish you happy'+new Date().toString() });
  }); 
  client.on('disconnect',function(){ 
   // clearInterval(interval); 
    console.log('Server has disconnected'); 
  }); 
  client.send('hello, I am the server');
});

结果:

客户端:

服务器端:

 

相关博文:SSE及相关技术(web sockets, long polling等)

 

 

 

posted @ 2014-05-19 17:35  wishyouhappy  阅读(5665)  评论(0编辑  收藏  举报