概念:
一种通讯协议,全双工模式
客户端和服务端都可以主动发送数据,可以进行实时通讯,持久连接
区别http协议:推送模式是定时器Ajax请求,浏览器不断向服务器发送请求,服务端没法主动推送,造成数据变化更新不及时和宽带等资源的浪费
其他特点:
- 主动推送的消息可以是文本或者二进制数据
- 没有同源限制,不会出现跨域的问题
- 连接第一阶段的握手还是http协议
- 协议标识ws,安全加密是wss
如果建立一个websocket连接?
客户端:
var ws=new WebSocket(url,[protocol])
url是连接的地址,protocol是可接受的子协议,单个协议名字字符串或者协议数组
url必填,protocol选填
常用方法:
ws.onopen=()=>{
// 向服务器发送数据
ws.send(‘发送数据’)
console.log(‘数据发送...’)
}
ws.onmessage=(e)=>{
var data=e.data
console.log(‘数据已接收’)
}
ws.onclose=()=>{
console.log(‘关闭连接’)
}
服务端:(node实现)
安装websocket模块,npm install websocket
具体测试demo
新建项目文件夹,npm install websocket后出现node_modules依赖
新建index.html如下
新建index.js代码如下
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(3000, function() {
console.log((new Date()) + ' Server is listening on port 3000');
});
wsServer = new WebSocketServer({
httpServer: server,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false
});
function originIsAllowed(origin) {
// put logic here to detect whether the specified origin is allowed.
return true;
}
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
// Make sure we only accept requests from an allowed origin
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}
console.log('连接成功')
var connection = request.accept(null, request.origin);
console.log((new Date()) + ' Connection accepted.');
setTimeout(()=>{
connection.sendUTF('HI,客户端');
})
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
console.log('接收到消息')
connection.sendUTF(message.utf8Data);
}
else if (message.type === 'binary') {
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
connection.sendBytes(message.binaryData);
}
});
connection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
console.log('断开连接')
});
});
当前项目下命令行启动node服务,指令为node index.js回车
浏览器打开index.html,可看到控制台相应信息
网友评论