HTML5的新特性,用於雙向推送消息(例如網頁聊天,手機推送消息等)javascript
原理:html
有新的信息時服務器和客戶端能夠相互發送信息(Real-time traffic from the server to the client and from the client to the serverjava
說明:node
readyState:web
CONNECTING (0):表示還沒創建鏈接;
OPEN (1): 已經創建鏈接,能夠進行通信;
CLOSING (2):經過關閉握手,正在關閉鏈接;
CLOSED (3):鏈接已經關閉或沒法打開;npm
url: WebSocket 服務器的網絡地址,協議一般是」ws」或「wss(加密通訊)」,ruby
事件:服務器
- 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.例子:app
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");
});
結果:
客戶端:
服務器端: