WebSocket是什么题翰?
WebSocket是一種網(wǎng)絡(luò)通信協(xié)議,RFC6455定義了它的通信標(biāo)準(zhǔn)俊抵。
WebSocket是HTML5可以提供的一種在單個(gè)TCP連接上進(jìn)行全雙工通訊的協(xié)議湿右。
服務(wù)器代碼
var express = require('express');
var http = require('http');
var WebSocket = require('ws');
var app = express();
app.use(express.static(__dirname));
var server = http.createServer(app);
var wss = new WebSocket.Server({server});
wss.on('connection', function connection(ws) {
console.log('開始連接痰憎!');
ws.on('message', function incoming(data) {
console.log('接收到了消息骡澈!');
/**
* 把消息發(fā)送到所有的客戶端
* wss.clients獲取所有鏈接的客戶端
*/
wss.clients.forEach(function each(client) {
client.send(data);
});
});
});
server.listen(8000, function listening() {
console.log('服務(wù)器啟動(dòng)成功锅纺!');
});
客戶端代碼
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>在線聊天</title>
</head>
<body>
<input type="text" onblur="wsServer.onopen(this.value)">
<script>
var wsServer = new WebSocket('ws://127.0.0.1:8000');
wsServer.onopen = function (e) {
(typeof e == 'string') && wsServer.send(e);//向后臺(tái)發(fā)送數(shù)據(jù)
};
wsServer.onclose = function (e) {//當(dāng)鏈接關(guān)閉的時(shí)候觸發(fā)
};
wsServer.onmessage = function (e) {//后臺(tái)返回消息的時(shí)候觸發(fā)
console.log(e);
};
wsServer.onerror = function (e) {//錯(cuò)誤情況觸發(fā)
}
</script>
</body>
</html>