只要动手做起来,多投入时间和精力、耐心去研究,以大多人的智商加google,平时遇到的大部分问题我们都是可以自己解决的,大部分的知识我们都是可以掌握的。

我们都知道http协议是单向请求的,无法实现双向通信,它只能从客户端发送请求,然后服务端再响应请求,无法做到服务端主动向客户端去推送消息。

尽管可以通过setTimeout/setInterval轮询的方式来不断去刷新获取服务端的数据,但是轮询的效率低,非常浪费资源。webscoket就是为了解决这一问题而存在的。

webscoket的特点:

1、建立在Tcp协议之上

2、与http协议有着很好的兼容性

3、通信高效,因为它的数据格式比较轻量、性能开销小

4、可以发送文本和二进制数据

5、没有同源限制

6、协议标识符是ws

简单的通信原理如下

客户端的实现:

浏览器端的实现

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>WebSocket</title>
</head>
<body>
<h1>Echo Test</h1>
<input id="sendTxt" type="text"/>
<button id="sendBtn">发送</button>
<div id="recv"></div>
<script type="text/javascript"> var WebSocket = new WebSocket("ws://localhost:8080");
WebSocket.onopen = function(){
console.log('websocket open');
document.getElementById("recv").innerHTML = "Connected";
}
WebSocket.onclose = function(){
console.log('websocket close');
}
WebSocket.onmessage = function(e){
console.log(e.data);
document.getElementById("recv").innerHTML = e.data;
}
document.getElementById("sendBtn").onclick = function(){
var txt = document.getElementById("sendTxt").value;
WebSocket.send(txt);
}
</script>
</body>
</html>

 

服务端实现:

nodejs搭建服务器,可以参考git上的《一起学nodejs》搭建服务器

文件目录下 npm install webscoket

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(8080, function() {
console.log((new Date()) + ' Server is listening on port 8080');
}); 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;
} var connection = request.accept('', request.origin);
console.log((new Date()) + ' Connection accepted.');
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
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.');
});
});

  

参考资料:

客户端(浏览器端)实现参考阮一峰:http://www.ruanyifeng.com/blog/2017/05/websocket.html

最新文章

  1. Apache SolrCloud安装
  2. FastDFS在centos上的安装配置与使用
  3. Linux系统编程@进程通信(一)
  4. 对象属性操作-包含kvc---ios
  5. HDU 1023 Train Problem II (卡特兰数,经典)
  6. MYSQL建立索引需要注意几点
  7. 转 Android 4.0后,自定义Title报错 You cannot combine custom titles with other title feature
  8. 纯CSS3代码实现简单的图片轮播
  9. Ugly Number II 解答
  10. 关于google的C++ coding style
  11. Inhouse interview(websense)
  12. vue组件,撸第一个
  13. 实用收藏Linux命令备忘
  14. Golang开发环境搭建(Notepad++、LiteIDE两种方式以及martini框架使用)
  15. OpenCV与Qt的环境搭建及Demo
  16. android 资源文字ids的作用
  17. OpenGL ES Shader语言中的函数不支持递归
  18. 当前数据库普遍使用wait-for graph等待图来进行死锁检测
  19. HDU 4691 Front compression (2013多校9 1006题 后缀数组)
  20. Linux静态库和共享库【转】

热门文章

  1. 改变html元素
  2. P1242 新汉诺塔(搜索+模拟退火)
  3. NYOJ 737:石子合并(一)(区间dp)
  4. hibernate中带查询条件的分页
  5. day 56 jQuery学习
  6. 用Hi3518EV200板当spi烧录器
  7. dev 域名与 Chrome
  8. TypeScript 之 JSX
  9. 什么是 PWA?
  10. jmeter-场景-上传文件-send-a-file