HTML5 Web Workers、Socket之网站也能多线程的实现

现在由于Web开发的需求越来越广泛,异步请求和并发、预处理等等都是提高了对网页处理复杂的业务能力和大数据的需求,所以有了很多高并发和异步处理的插件和方式出来,自从HTML5出来也带来很大的进步、改变,下面我们就来说说Web Workers和Web Socket的好处。

一、Web Workers是在HTML5中新增的,用来在web应用程序中实现后台处理的一种技术。

在HTML4中,js创建的程序都是单线程的,如果花费时间比较长的话web界面就会长时间没有响应,最恶劣的情况还会跳出一个脚本提示框:

提示脚本运行时间过长,是否继续。。。。于是就引出了本文的主角:Web Workers API

你可以在你的 worker 线程中运行任意的代码,以下情况除外:你不能直接在 worker 线程中操纵 DOM 元素, 或者使用某些 window 对象中默认的方法和属性。 但是 window 对象中很多的方法和属性你是可以使用的,包括 WebSockets,以及诸如 IndexedDB 和 FireFox OS 中独有的 Data Store API 这一类数据存储机制。

使用这个API用户可以非常容易的创建在后台运行的线程,要创建后台程序很简单:

1.接下来我们测试一个简单的求和例子,先来一个普通大众的求和方法:

以上方式很容易造成浏览器卡死或内存溢出

2.由于HTML5的特性,我们可以很容易的使用web worker,就不会产生以上的问题了:

传入Worker的文件内容为:

运行后,结果很快的弹出:

3.使用worker来实现一个比较复杂的计算,100内能被3整除的整数:与线程进行数据交互

test1.js的代码

test2.js的代码

程序生成的结果为:

程序逻辑描述:

这里用了个线程嵌套

首先执行前台程序,这里初始化了一个子线程“test1”用于将100个数组初始化

然后子线程test1又初始化了子线程test2(用于遍历数组,取出能被3整除的数字,组成字符串),test1将数组数据传给test2

test2 接收test1数据,计算后将将字符串转给test1,test1转给前台,前台执行自己的逻辑

流程结束

二、WebSocket protocol 是HTML5一种新的协议。

它实现了浏览器与服务器全双工通信(full-duple)。一开始的握手需要借助HTTP请求完成。原理参照:

https://www.zhihu.com/question/20215561

实例参照:

HTML5 WebSockets 基础使用教程

http://blog.csdn.net/charlene0824/article/details/51926463

Node.js + Web Socket 即时聊天程序:

http://www.cnblogs.com/Wayou/p/hichat_built_with_nodejs_socket.html

 

 

 

3 Comments

  1. limbnow201

    2017年4月22日 上午9:27, 回复

    I’m writing to make you be aware of what a amazing experience my wife’s girl had browsing your webblog. She came to understand plenty of issues, which included what it is like to have an incredible helping mood to make the others with no trouble learn some tortuous topics. You really exceeded our expectations. Many thanks for presenting such practical, trustworthy, educational and also cool guidance on your topic to Gloria.

  2. limbnow201

    2017年4月24日 上午3:04, 回复

    My husband and i felt now cheerful Edward managed to finish up his basic research through the entire ideas he got through your web site. It is now and again perplexing to just be offering thoughts which other people could have been trying to sell. And now we fully grasp we need the blog owner to appreciate because of that. The entire illustrations you made, the simple site menu, the relationships your site help promote – it’s everything fabulous, and it is making our son in addition to our family feel that that idea is amusing, which is certainly seriously essential. Many thanks for everything!

  3. limbnow201

    2017年4月24日 下午11:14, 回复

    A lot of thanks for each of your effort on this web site. Kate delights in conducting research and it is easy to see why. My partner and i notice all of the powerful mode you offer very useful solutions via the website and strongly encourage response from other ones on the point then our girl is always discovering a lot. Enjoy the remaining portion of the year. You have been carrying out a fabulous job.

Leave a comment

(*) Required, Your email will not be published