只要动手做起来,多投入时间和精力、耐心去研究,以大多人的智商加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

webscoket通信初步(一)的更多相关文章

  1. win32 线程通信初步

    // 线程通信机制.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #define NUM_THREADS 10 #include < ...

  2. 前端后端通信初步尝试(javascript - flask)

    在某项目中,需要使用python flask做后端功能开发,web提供功能入口. 此时需要使用Ajax通信. 由于以前从未接触过网络传输,记录了一些基础知识. 资料参考<HTML5+CSS3+J ...

  3. 阿里云负载不支持 WebSocket 协议与 WSS 和 Nginx 配置问题

    WebSocket 是 HTML5 下一种新的协议.它实现了浏览器与服务器全双工通信,能更好的节省服务器资源和带宽并达到实时通讯的目的.它与HTTP一样通过已建立的TCP连接来传输数据,但是它和HTT ...

  4. node的socket.io类库概述

    socket.io是一个简单的小类库,该类库实现的功能类似于node中的net模块所实现的功能. 这些功能包括websocket通信,xhr轮询,jsonp轮询等. socket类库可以接受所有与服务 ...

  5. Netty之WebSocket和四种IO介绍

    Netty简介 一.什么是netty? 高性能 事件驱动 异步非堵塞 基于NIO的客户端,服务器端编程框架 稳定性和伸缩性 二.Netty的使用场景 高性能领域   多线程并发领域   异步通信领域 ...

  6. VsCode插件开发之插件初步通信

    参考了Egret Wing,想像Egret Wing那样在上方titlebar最右边上面增加一个menu(这个menu相对于一个按钮,当点击这个按钮时会出现一个window弹框,这个window弹框里 ...

  7. 基于C/S架构的3D对战网络游戏C++框架 _05搭建系统开发环境与Boost智能指针、内存池初步了解

    本系列博客主要是以对战游戏为背景介绍3D对战网络游戏常用的开发技术以及C++高级编程技巧,有了这些知识,就可以开发出中小型游戏项目或3D工业仿真项目. 笔者将分为以下三个部分向大家介绍(每日更新): ...

  8. Azure底层架构的初步分析

    之所以要写这样的一篇博文的目的是对于大多数搞IT的人来说,一般都会对这个topic很感兴趣,因为底层架构直接关乎到一个公有云平台的performance,其实最主要的原因是我们的客户对此也非常感兴趣, ...

  9. webScoket的浅短的认识

    在一般的发送数据请求的时候都是用的http协议,但是对于类似即时聊天,需要客户端与服务器不间断的交互的时候对于http协议来说就不太适用了.因为http协议无法主动把数据发到客户端,而且客户端发送请求 ...

随机推荐

  1. 51Nod 1084:矩阵取数问题 V2(多维DP)

    1084 矩阵取数问题 V2  基准时间限制:2 秒 空间限制:131072 KB 分值: 80 难度:5级算法题  收藏  关注 一个M*N矩阵中有不同的正整数,经过这个格子,就能获得相应价值的奖励 ...

  2. A Spy in the Metro(UVA 1025 ACM/ICPC World Finals2003)

    ---恢复内容开始--- 题意:有n(2<=n<=50)个车站,从左到右编号为1~n,有M1辆列车从第1站向右开,还有M2辆列车从第N站向左开.在时刻0,间谍从第1站出发,目的是在时刻T( ...

  3. 大型网站系统与Java中间件实践读书笔记

    转载:http://blog.csdn.net/ioscodelover/article/details/45047869 1.分布式系统相对集中式而言,是指多台计算机互相通过消息通信进行协作而对外提 ...

  4. Count the Sheep 思维题

    Altough Skipping the class is happy, the new term still can drive luras anxious which is of course b ...

  5. 【BZOJ2820】ygy的gcd

    不知道为什么不想写总结,只是(因为是用别人的权限号交的所以)屯一个代码 #include<iostream> #include<cstdio> #include<algo ...

  6. The Carbon driver has not been ported to 64bits, and very few parts of Windows.Forms will work properly, or at all Stacktrace

    解决地址:https://stackoverflow.com/questions/45776247/mono32-wont-work-mono64-throws-errors 应该是电脑的位与安装的m ...

  7. Java基础四(switch、数组、)

    1.流程控制语句switch2.数组3.随机点名器案例 ###01switch语句解构 * A:switch语句解构 * a:switch只能针对某个表达式的值作出判断,从而决定程序执行哪一段代码. ...

  8. DevExpress 中 设置 labelControl 的背景透明到图片的方法

    labelControl 中的 backColor 可以设置为: TransParent 当设置为: Transparent 的时候,labelControl 的背景依然为 主form的背景颜色 ,研 ...

  9. egret学习

    1.egret wing4.0不能创建egret游戏项目, 重置了引擎之后就可以了 2.入门介绍:http://developer.egret.com/cn/github/egret-docs/Eng ...

  10. ML(6)——改进机器学习算法

    现在我们要预测的是未来的房价,假设选择了回归模型,使用的损失函数是: 通过梯度下降或其它方法训练出了模型函数hθ(x),当使用hθ(x)预测新数据时,发现准确率非常低,此时如何处理? 在前面的章节中我 ...