WebSocket 教程

WebSocket 是一种网络通信协议,很多高级功能都需要它。

本文介绍 WebSocket 协议的使用方法。

一、为什么需要 WebSocket?

初次接触 WebSocket 的人,都会问同样的问题:我们已经有了 HTTP 协议,为什么还需要另一个协议?它能带来什么好处?

答案很简单,因为 HTTP 协议有一个缺陷:通信只能由客户端发起。

举例来说,我们想了解今天的天气,只能是客户端向服务器发出请求,服务器返回查询结果。HTTP 协议做不到服务器主动向客户端推送信息。

这种单向请求的特点,注定了如果服务器有连续的状态变化,客户端要获知就非常麻烦。我们只能使用“轮询”:每隔一段时候,就发出一个询问,了解服务器有没有新的信息。最典型的场景就是聊天室。

轮询的效率低,非常浪费资源(因为必须不停连接,或者 HTTP 连接始终打开)。因此,工程师们一直在思考,有没有更好的方法。WebSocket 就是这样发明的。

二、简介

WebSocket 协议在2008年诞生,2011年成为国际标准。所有浏览器都已经支持了。

它的最大特点就是,服务器可以主动向客户端推送信息,客户端也可以主动向服务器发送信息,是真正的双向平等对话,属于服务器推送技术的一种。

其他特点包括:

(1)建立在 TCP 协议之上,服务器端的实现比较容易。

(2)与 HTTP 协议有着良好的兼容性。默认端口也是80和443,并且握手阶段采用 HTTP 协议,因此握手时不容易屏蔽,能通过各种 HTTP 代理服务器。

(3)数据格式比较轻量,性能开销小,通信高效。

(4)可以发送文本,也可以发送二进制数据。

(5)没有同源限制,客户端可以与任意服务器通信。

(6)协议标识符是ws(如果加密,则为wss),服务器网址就是 URL。

ws://example.com:80/some/path

三、客户端的简单示例

WebSocket 的用法相当简单。

下面是一个网页脚本的例子(点击这里看运行结果),基本上一眼就能明白。

var ws = new WebSocket("wss://echo.websocket.org");

ws.onopen = function(evt) { 
  console.log("Connection open ..."); 
  ws.send("Hello WebSockets!");
};

ws.onmessage = function(evt) {
  console.log( "Received Message: " + evt.data);
  ws.close();
};

ws.onclose = function(evt) {
  console.log("Connection closed.");
};      

四、客户端的 API

WebSocket 客户端的 API 如下。

4.1 WebSocket 构造函数

WebSocket 对象作为一个构造函数,用于新建 WebSocket 实例。

var ws = new WebSocket('ws://localhost:8080');

执行上面语句之后,客户端就会与服务器进行连接。

实例对象的所有属性和方法清单,参见这里

4.2 webSocket.readyState

readyState属性返回实例对象的当前状态,共有四种。

  • CONNECTING:值为0,表示正在连接。
  • OPEN:值为1,表示连接成功,可以通信了。
  • CLOSING:值为2,表示连接正在关闭。
  • CLOSED:值为3,表示连接已经关闭,或者打开连接失败。

下面是一个示例。

switch (ws.readyState) {
  case WebSocket.CONNECTING:
    // do something
    break;
  case WebSocket.OPEN:
    // do something
    break;
  case WebSocket.CLOSING:
    // do something
    break;
  case WebSocket.CLOSED:
    // do something
    break;
  default:
    // this never happens
    break;
}

4.3 webSocket.onopen

实例对象的onopen属性,用于指定连接成功后的回调函数。

ws.onopen = function () {
  ws.send('Hello Server!');
}

如果要指定多个回调函数,可以使用addEventListener方法。

ws.addEventListener('open', function (event) {
  ws.send('Hello Server!');
});

4.4 webSocket.onclose

实例对象的onclose属性,用于指定连接关闭后的回调函数。

ws.onclose = function(event) {
  var code = event.code;
  var reason = event.reason;
  var wasClean = event.wasClean;
  // handle close event
};

ws.addEventListener("close", function(event) {
  var code = event.code;
  var reason = event.reason;
  var wasClean = event.wasClean;
  // handle close event
});

4.5 webSocket.onmessage

实例对象的onmessage属性,用于指定收到服务器数据后的回调函数。

ws.onmessage = function(event) {
  var data = event.data;
  // 处理数据
};

ws.addEventListener("message", function(event) {
  var data = event.data;
  // 处理数据
});

注意,服务器数据可能是文本,也可能是二进制数据(blob对象或Arraybuffer对象)。

ws.onmessage = function(event){
  if(typeof event.data === String) {
    console.log("Received data string");
  }

  if(event.data instanceof ArrayBuffer){
    var buffer = event.data;
    console.log("Received arraybuffer");
  }
}

除了动态判断收到的数据类型,也可以使用binaryType属性,显式指定收到的二进制数据类型。


// 收到的是 blob 数据
ws.binaryType = "blob";
ws.onmessage = function(e) {
  console.log(e.data.size);
};

// 收到的是 ArrayBuffer 数据
ws.binaryType = "arraybuffer";
ws.onmessage = function(e) {
  console.log(e.data.byteLength);
};

4.6 webSocket.send()

实例对象的send()方法用于向服务器发送数据。

发送文本的例子。

ws.send('your message');

发送 Blob 对象的例子。

var file = document
  .querySelector('input[type="file"]')
  .files[0];
ws.send(file);

发送 ArrayBuffer 对象的例子。


// Sending canvas ImageData as ArrayBuffer
var img = canvas_context.getImageData(0, 0, 400, 320);
var binary = new Uint8Array(img.data.length);
for (var i = 0; i < img.data.length; i++) {
  binary[i] = img.data[i];
}
ws.send(binary.buffer);

4.7 webSocket.bufferedAmount

实例对象的bufferedAmount属性,表示还有多少字节的二进制数据没有发送出去。它可以用来判断发送是否结束。

var data = new ArrayBuffer(10000000);
socket.send(data);

if (socket.bufferedAmount === 0) {
  // 发送完毕
} else {
  // 发送还没结束
}

4.8 webSocket.onerror

实例对象的onerror属性,用于指定报错时的回调函数。

socket.onerror = function(event) {
  // handle error event
};

socket.addEventListener("error", function(event) {
  // handle error event
});

五、服务端的实现

WebSocket 服务器的实现,可以查看维基百科的列表

常用的 Node 实现有以下三种。

具体的用法请查看它们的文档,这里不详细介绍了。

六、WebSocketd

下面,我要推荐一款非常特别的 WebSocket 服务器:Websocketd

它的最大特点,就是后台脚本不限语言,标准输入(stdin)就是 WebSocket 的输入,标准输出(stdout)就是 WebSocket 的输出。

举例来说,下面是一个 Bash 脚本counter.sh。

#!/bin/bash

echo 1
sleep 1

echo 2
sleep 1

echo 3

命令行下运行这个脚本,会输出1、2、3,每个值之间间隔1秒。

$ bash ./counter.sh
1
2
3

现在,启动websocketd,指定这个脚本作为服务。

$ websocketd --port=8080 bash ./counter.sh

上面的命令会启动一个 WebSocket 服务器,端口是8080。每当客户端连接这个服务器,就会执行counter.sh脚本,并将它的输出推送给客户端。

var ws = new WebSocket('ws://localhost:8080/');

ws.onmessage = function(event) {
  console.log(event.data);
};

上面是客户端的 JavaScript 代码,运行之后会在控制台依次输出1、2、3。

有了它,就可以很方便地将命令行的输出,发给浏览器。

$ websocketd --port=8080 ls

上面的命令会执行ls命令,从而将当前目录的内容,发给浏览器。使用这种方式实时监控服务器,简直是轻而易举(代码)。

更多的用法可以参考官方示例

websocketd 的实质,就是命令行的 WebSocket 代理。只要命令行可以执行的程序,都可以通过它与浏览器进行 WebSocket 通信。下面是一个 Node 实现的回声服务greeter.js

process.stdin.setEncoding('utf8');

process.stdin.on('readable', function() {
  var chunk = process.stdin.read();
  if (chunk !== null) {
    process.stdout.write('data: ' + chunk);
  }
});

启动这个脚本的命令如下。

$ websocketd --port=8080 node ./greeter.js

官方仓库还有其他各种语言的例子。

七、参考链接

(完)

1,530 Replies to “WebSocket 教程”

  1. I don’t even know how I ended up here, but I thought this post was good. I don’t know who you are but certainly you are going to a famous blogger if you aren’t already ?? Cheers!
    nmd r1

  2. Their website will look like it’s carefully maintained, and have a call to action on nearly each web page. In order to make your home secured, it is better to spendthat extra dime on special front door lock than to restrain the money. Some heavy loads are fragile and if handled carelessly, damages will occur.FLORIDA STATESean Maguire ended last season as the Seminoles’ starter, but he will have serious competition underclassmen with more upside. Are you going to, however, if you are well on a tight budget I would recommend you to definitely select reduce costs: besides, the grade of the look will not be affected the slightest bit, given that environmental surroundings is dark enough.

  3. <li><li>This might shorten your penis due to the curve. In most access, the greater reliable protection systems forhotels tend to be more expensive than the others. Jewelry dealers have made fortunes by popularizing specific designs, cultivating a demand, and continually raising the prices. Benefits Of Hotel Door Lock SystemPecora Hoy   Submitted 20140214 13:20:13 Hotel business is a people focused kind of business. The NREL is additionally equipped with aTechnology Transfer Office.

  4. One more thing I would like to mention is that in lieu of trying to match all your online degree courses on days that you complete work (considering that people are fatigued when they come home), try to receive most of your lessons on the week-ends and only a few courses in weekdays, even if it means taking some time away from your weekend break. This is beneficial because on the weekends, you will be a lot more rested and also concentrated on school work. Thx for the different recommendations I have figured out from your site.
    adidas nmd

  5. Definitely believe that which you said. Your favorite justification appeared to be on the internet the simplest thing to be aware of. I say to you, I definitely get irked while people consider worries that they just don’t know about. You managed to hit the nail upon the top and defined out the whole thing without having side effect , people can take a signal. Will probably be back to get more. Thanks
    nb shoes

  6. Thanks a lot for the helpful posting. It is also my opinion that mesothelioma cancer has an very long latency period, which means that signs and symptoms of the disease might not exactly emerge right until 30 to 50 years after the original exposure to mesothelioma. Pleural mesothelioma, that is certainly the most common style and has an effect on the area throughout the lungs, might result in shortness of breath, chest muscles pains, plus a persistent coughing, which may bring on coughing up our blood.
    adidas tubular shadow

  7. When I originally commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get several emails with the same comment. Is there any way you can remove me from that service? Cheers!
    curry 2

  8. Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point. You clearly know what youre talking about, why waste your intelligence on just posting videos to your weblog when you could be giving us something informative to read?
    adidas superstar

  9. If you for example you need the services of heavy machines, they will provide both machines and operators. Their website will look like it’s carefully maintained, and have a call to action on nearly each web page. So, the professional will be the one who will come to settle it as soon as they witness the physical condition and its specification. Lastly, a good web design company’s website will be useful and easy to navigate. The reservoir will hold as much chemical as the up to 4 drums that are placed on them.

  10. It’s perfect time to make some plans for the future and it’s time to be happy. I have read this post and if I could I want to suggest you few interesting things or advice. Perhaps you could write next articles referring to this article. I want to read more things about it!
    adidas superstar

  11. Some alternative rings even use other precious ingredients, like rare tree wood or alternative metals, to create incredible value without increasing the price for you.It appears now that people are open to the idea that without a healthy diet, performance may not be expected to be excellent.<br >The reason: <br >(1)The lock is not adjusted well, Seal lax and make the powder pour.Think you’re ready to explore your options? Don’t hesitate to contact us today at info@oliviaewing.4.

  12. Having strong, effective keywords that relate well to your content is the best way to draw new visitors to your site, as it will help you rank higher in search engines. Apparently, the Laboratory got the hint, because soon after the State of the Union Address, everyone was rehired. It keeps the employees safer by not exposing them to any chemicals, dangerous or not. Therefore the penis will be get straightened on gradual process and therefore is a faster and healthier way of straightening your curved penis.鈥?The federallybacked Laboratory directly helps along the United States’ objectives for discovering renewable alternative fuels for powering our economy and our lifestyles.

  13. I have to get across my admiration for your kindness supporting persons that must have assistance with this important content. Your very own dedication to passing the message around has been incredibly significant and has in every case empowered others like me to arrive at their goals. Your new valuable report implies much a person like me and much more to my office colleagues. Warm regards; from everyone of us.
    puma rihanna

  14. The best treadmill to have is the home treadmill because research shows you burn more calories. If a web design company’s own web site is not well managed, why trust them to work with yours?2) Willingness to Work with YouA web design company should have content on their website that’s geared towards you, the potential customer.<p>Best treadmill seekers: here’s news. However, if you want to stay classy then you can go for among several other portable film drying cabinets which can be especially intended for this operation.Indeed, the coming years show more promise of worldwide sports nutrition because of heightened awareness and interest in it.

  15. Good – I should certainly pronounce, impressed with your website. I had no trouble navigating through all tabs and related info ended up being truly easy to do to access. I recently found what I hoped for before you know it at all. Quite unusual. Is likely to appreciate it for those who add forums or something, web site theme . a tones way for your customer to communicate. Nice task.
    NMD R1 Primeknit

  16. There are actually a variety of particulars like that to take into consideration. That is a nice point to bring up. I provide the ideas above as general inspiration however clearly there are questions like the one you convey up the place the most important factor can be working in honest good faith. I don?t know if greatest practices have emerged around issues like that, however I am sure that your job is clearly identified as a fair game. Each boys and girls feel the impression of just a moment’s pleasure, for the remainder of their lives.
    kobe bryant shoes

  17. comcrusherScrewclassifier. This makes both ends get their advantages. These areas span from understanding renewable resources for energy, to the conversion of these resources to renewable electricity and fuels, and ultimately to the use of renewable electricity and fuels in homes, commercial buildings, and vehicles.Repair of Signs:It is possible for signs to wear out over time. What you want instead is the treadmill that helps you burn more calories ? and that according to research is the one at home.

  18. I just hope to inform you that I am new to writing and genuinely enjoyed your webpage. Quite possibly I am prone to store your blog post . You seriously have stunning article material. Get Pleasure From it for telling with us your favorite domain page
    ugg 5250

  19. Knight finally written pledge to fulfill a military order!Owen Jefferson suspected the contradiction, huang zhan anger: don’t win playoff team and the team retired showdown between the more and more intense, will the rockets in just eliminated the spurs tomorrow will come and warriors in the first fight
    kyrie irving shoes

  20. I have seen loads of useful items on your internet site about desktops. However, I have the thoughts and opinions that laptop computers are still not nearly powerful sufficiently to be a good selection if you frequently do jobs that require a lot of power, like video modifying. But for world wide web surfing, word processing, and a lot other prevalent computer functions they are perfectly, provided you don’t mind your little friend screen size. Many thanks sharing your notions.
    yeezy boost 350

  21. Because Michael Owen at the side of huang zhan, so his nickname called small report.The earliest Owen left the impression of the world, is probably the flashy passing movements and dazzling breakthroughs, remember in the rookie challenge, he drew down two slipped past knight
    kyire 3

  22. Thanks so much for giving everyone an extremely terrific chance to read in detail from this site. It is always so ideal and jam-packed with a lot of fun for me personally and my office colleagues to search the blog particularly thrice a week to study the fresh tips you will have. Of course, I’m so always happy with all the extraordinary concepts served by you. Certain two areas on this page are indeed the very best I’ve ever had.
    adidas originals

  23. “I don’t think eastern conference finals will be a long war, knight’s strength is too strong. The celtics nobody with lebron, they even Owen this level of star all have no, they are really no one can stop the knight.
    kd 10

  24. For Jordan and gregg popovich comments James never hit back, but just yesterday in the knight’s basketball stadium set aside a James training video, far look like illusions emerged both Owen, a carefully look just know is James
    curry 4

  25. Obviously, the right to occupy a team-high 21.6 shots of Michael Owen, but failed to hit as James scores, this let a person feel, Owen has become a “cancer” of the knight.But many fans also feel,
    curry 3

  26. I have realized that over the course of building a relationship with real estate homeowners, you’ll be able to get them to understand that, in most real estate exchange, a commission rate is paid. In the end, FSBO sellers tend not to “save” the commission rate. Rather, they fight to earn the commission by means of doing the agent’s task. In doing so, they shell out their money and also time to execute, as best they will, the obligations of an real estate agent. Those obligations include revealing the home through marketing, representing the home to willing buyers, constructing a sense of buyer desperation in order to make prompt an offer, arranging home inspections, managing qualification inspections with the financial institution, supervising fixes, and aiding the closing.
    lebron james shoes

  27. For Jordan and gregg popovich comments James never hit back, but just yesterday in the knight’s basketball stadium set aside a James training video, far look like illusions emerged both Owen, a carefully look just know is James
    kyrie 1

  28. NBA players in addition to playing badly, and also an art cells, for two consecutive years in the NBA finals two teams join forces with the warriors and knight, but only two dancers, two teams played neck and neck, dancing is close, take a look at
    kyrie 4

  29. Number of players not invited to combine but drafted Year Total Rd: 1 2 3 4 5 6 7 2008 36 0 0 0 3 4 11 18 2007 39 0 0 1 5 8 11 14 2006 33 0 0 0 3 3 9 18 2005 34 0 1 0 4 3 6 20 2004 37 0 1 1 3 1 8 23 2003 43 0 1 3 1 5 13 20 2002 48 0 1 1 3 8 16 19 2001 30 0 0 0 2 6 8 14 2000 51 0 0 3 3 10 11 24 1999 42 0 0 2 5 7 11 17 Other facts about draftees not invited to combine: » Of the 393 players drafted who were not invited to the combine, there were 15 quarterbacks, 16 running backs, 9 fullbacks, 52 wide receivers, 26 tight ends, 14 centers, 25 offensive guards, 18 offensive tackles, 38 defensive ends, 35 defensive tackles, 13 inside linebackers, 35 outside linebackers, 41 cornerbacks, 45 safeties, 7 kickers and 4 punters.
    Wholesale Baseball Jerseys China

  30. Knight finally written pledge to fulfill a military order!Owen Jefferson suspected the contradiction, huang zhan anger: don’t win playoff team and the team retired showdown between the more and more intense, will the rockets in just eliminated the spurs tomorrow will come and warriors in the first fight
    stephen curry shoes

  31. I simply wanted to thank you yet again for that amazing website you have built here. It can be full of ideas for those who are really interested in this particular subject, particularly this very post. You’re really all actually sweet and also thoughtful of others and reading your site posts is a great delight in my opinion. And what a generous surprise! Mary and I really have fun making use of your guidelines in what we should instead do in the near future. Our listing is a kilometer long so your tips are going to be put to excellent use.

  32. One other thing to point out is that an online business administration training course is designed for students to be able to without problems proceed to bachelors degree education. The Ninety credit college degree meets the other bachelor education requirements then when you earn the associate of arts in BA online, you will have access to the most up-to-date technologies in such a field. Some reasons why students would like to get their associate degree in business is because they’re interested in the field and want to receive the general instruction necessary in advance of jumping right into a bachelor diploma program. Thanks alot : ) for the tips you provide as part of your blog.

  33. I have learned many important things as a result of your post. I’d personally also like to mention that there may be situation where you will have a loan and never need a cosigner such as a Federal government Student Aid Loan. However, if you are getting credit through a standard loan company then you need to be made ready to have a cosigner ready to allow you to. The lenders are going to base their very own decision on a few issues but the most important will be your credit history. There are some financial institutions that will likewise look at your job history and decide based on this but in many cases it will depend on your ranking.

  34. I am really inspired along with your writing skills as neatly as with the structure for your weblog. Is this a paid subject matter or did you customize it your self? Either way keep up the excellent high quality writing, it is rare to look a great blog like this one nowadays.

  35. According to The Fear of The Sword, The knight’s point guard deron Williams is a fan of MMA (mixed), compared to The basketball game, deron prefer to watch The ultimate fighting championship.Deron Williams recently said in an interview, he retired from the NBA
    ultra boost 4.0

  36. I just want to mention I am all new to blogging and site-building and honestly loved this web blog. Almost certainly I’m likely to bookmark your blog . You actually have fabulous article content. With thanks for sharing with us your blog site.

  37. vlmkozhn billige fotballdrakter umsfgdrx maglie calcio a poco prezzo iuycdfqn fodboldtrojer ejufgaqh billiga fotbollstrjor
    wtbqdcjr maglie calcio hzxwbmck fotbollstrjor fcptoxur billige fodboldtrojer cagsrqyt billige fotballdrakter

  38. What’s up everyone, I be familiar with YouTube video consists of fewer bytes of memory due to that its quality is poor, but this YouTube video has impressive picture features.