1.什么是WebSocket协议

RFC6455文档的表述如下:

The WebSocket Protocol enables two-way communication between a client running untrusted code in a controlled environment to a remote host that has opted-in to communications from that code. The security model used for this is the origin-based security model commonly used by web browsers. The protocol consists of an opening handshake followed by basic message framing, layered over TCP. The goal of this technology is to provide a mechanism for browser-based applications that need two-way communication with servers that does not rely on opening multiple HTTP connections.

大意是说WebSocket是一个基于TCP协议的全双工的应用层协议,主要用于Web浏览器,其目的是使基于浏览器、需要全双工通信的web应用不再依赖于多个HTTP连接。

2.应用WebSocket

设想这样一个场景,一个基于B/S架构的应用,其功能是服务器主动向浏览器定时发送一个消息,应该怎么做?由于HTTP协议只能由客户端发起请求,服务器端响应请求建立连接,所以通过HTTP协议实现服务器主动推送消息有一定的难度,可以通过浏览器客户端定时向服务器发送HTTP请求来实现,Comet就是基于这种方式,实际上这并不是真正的“服务器主动”。然而依靠WebSocket,我们能够轻易的做到这一点。

现在WebSocket的支持情况如下:

1.服务器端

  1. IIS 7.0+
  2. Tomcat 7.0.5+
  3. Jetty t.0+
  4. WebLogic 12c
  5. WebSphere 8.0+

2.浏览器端

  1. Chrome 4+
  2. FireFox 5+
  3. IE 10+
  4. Safari IOS 5+
  5. Android Browser Android 4.5+

下面我们将利用WebSocket实现一个简单的java webapp,其功能是服务器主动向浏览器发送三条消息。服务器为Tomcat 8.5.4,除此之外,要为我们的app引入支持WebSocket的jar包---websocket-api.jar。如需观察其效果,请移步http://139.129.95.147/TestWebSocket/

代码如下:

前端:

 <!DOCTYPE html>
<html>
<head>
<title>Testing websockets</title>
</head>
<body>
<div>
<input type="submit" value="Start" onclick="start()" />
</div>
<div id="messages"></div>
<script type="text/javascript">
var webSocket =
new WebSocket('ws://139.129.95.147/TestWebSocket/websocket');
webSocket.onerror = function(event) {
onError(event)
};
webSocket.onopen = function(event) {
onOpen(event)
};
webSocket.onmessage = function(event) {
onMessage(event)
};
function onMessage(event) {
document.getElementById('messages').innerHTML
+= '<br />' + event.data;
}
function onOpen(event) {
document.getElementById('messages').innerHTML
= 'Connection established';
}
function onError(event) {
alert(event.data);
}
function start() {
webSocket.send('hello');
return false;
}
</script>
</body>
</html>

index.html

后端:

 import java.io.IOException;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/websocket")
public class TestWebSocket {
@OnMessage
public void onMessage(String message, Session session)
throws IOException, InterruptedException { // Print the client message for testing purposes
System.out.println("Received: " + message); // Send the first message to the client
session.getBasicRemote().sendText("This is the first server message"); // Send 3 messages to the client every 5 seconds
int sentMessages = 0;
while(sentMessages < 3){
Thread.sleep(5000);
session.getBasicRemote().
sendText("This is an intermediate server message. Count: "
+ sentMessages);
sentMessages++;
} // Send a final message to the client
session.getBasicRemote().sendText("This is the last server message");
} @OnOpen
public void onOpen() {
System.out.println("Client connected");
}
@OnClose
public void onClose() {
System.out.println("Connection closed");
}
}

在Tomcat中使用WebSocket,首先需要在服务器端建立一个endpoint,语法为

@ServerEndpoint("/websocket")

然后在前端根据这个endpoint的url获取一个WebSocket对象,然后调用其相关方法即可。由于代码较为简单,在本文中不在赘述,我会在后续文章中详细分析。

3.WebSocket和TCP、HTTP的关系

WebSocket是一个独立的、基于TCP协议的应用层协议,它和HTTP协议唯一的关系就是WebSocket协议的握手建立连接的过程是由HTTP服务器实现的,并且HTTP服务器将之视为HTTP协议的一个升级版。

PS:我的大部分文章首发在知乎专栏:关于计算机的一些事,欢迎大家关注

初识WebSocket协议的更多相关文章

  1. WebSocket协议详解及应用

    WebSocket协议详解及应用(七)-WebSocket协议关闭帧 本篇介绍WebSocket协议的关闭帧,包括客户端及服务器如何发送并处理关闭帧.关闭帧错误码及错误处理方法.本篇内容主要翻译自RF ...

  2. Websocket 协议解析

    WebSocket protocol 是HTML5一种新的协议.它是实现了浏览器与服务器全双工通信(full-duplex).          现 很多网站为了实现即时通讯,所用的技术都是轮询(po ...

  3. 一步一步学WebSocket (一) 初识WebSocket

    众所周知,Http协议是无状态的,并且是基于Request/Response的方式与服务器进行交互,也就是我们常说的单工模式.但是随着互联网的发展,浏览器与服务端进行双向通信需求的增加,长轮询向服务器 ...

  4. WebSocket协议开发

    一直以来,网络在很大程度上都是围绕着HTTP的请求/响应模式而构建的.客户端加载一个网页,然后直到用户点击下一页之前,什么都不会发生.在2005年左右,Ajax开始让网络变得更加动态了.但所有的HTT ...

  5. 初识WebSocket

    众所周知,Http协议是无状态的,并且是基于Request/Response的方式与服务器进行交互,也就是我们常说的单工模式.但是随着互联 网的发展,浏览器与服务端进行双向通信需求的增加,长轮询向服务 ...

  6. Websocket协议的学习、调研和实现

    本文章同时发在 cpper.info. 1. websocket是什么 Websocket是html5提出的一个协议规范,参考rfc6455. websocket约定了一个通信的规范,通过一个握手的机 ...

  7. 初识HTTP协议

    本篇文章从概念上初识HTTP协议,参考链接:http://www.runoob.com/http/http-tutorial.html 目录: 一.HTTP协议    HTTP 工作原理    HTT ...

  8. python测试基于websocket协议的即时通讯接口

    随着html5的广泛应用,基于websocket协议的即时通讯有了越来越多的使用场景,本文使用python中的websocket-client模块来做相关的接口测试 import webclient ...

  9. Websocket协议之php实现

    前面学习了HTML5中websocket的握手协议.打开和关闭连接等基础内容,最近用php实现了与浏览器websocket的双向通信.在学习概念的时候觉得看懂了的内容,真正在实践过程中还是会遇到各种问 ...

随机推荐

  1. laravel 控制器里 redirect url地址传两个参数的方法

    public function red_search() { $url=Request::all(); return redirect('search/'.$url['category'].'/'.$ ...

  2. 使用File类递归列出E盘下全部文件

    import java.io.File;public class FileListTest { public void tree(File file){ if(file.listFiles()!=nu ...

  3. Bitmap旋转方法

    最近在做一个ORC图片解析的功能,要求解析出数字 但是发现他解析只能解析横着的图片,然后我拍照的时候拍的是竖直照片,当然你也可以去旋转照相机的屏幕 但是我这里为了方便选择的是竖直拍出来 然后,旋转下咯 ...

  4. Linux 文件基本属性

    Linux系统是一种典型的多用户系统,不同的用户处于不同的地位,拥有不同的权限.为了保护系统的安全性,Linux系统对不同的用户访问同一文件(包括目录文件)的权限做了不同的规定. 在Linux中我们可 ...

  5. Linux编程之驱动

    增加自己写的驱动程序:http://blog.chinaunix.net/uid-23065002-id-115739.html http://os.51cto.com/art/201108/2840 ...

  6. sql注入基于错误-单引号-字符型

    查找注入点 在url中: 1. ' 2. and 1=1/and 1=2 3. 随即输入(整形) 4. -1/+1回显上下页面(整形) 5. and sleep(5) (判断页面返回时间)   判断有 ...

  7. codeforces 725D . Contest Balloons(贪心+优先队列)

    题目链接:codeforces 725D . Contest Balloons 先按气球数从大到小排序求出初始名次,并把名次排在第一队前面的队放入优先队列,按w-t-1值从小到大优先,然后依次给气球给 ...

  8. 安装xampp 后 发现 apache 启动不起来

    这种事情很常见的.启动不起来 第一,改个端口

  9. JQ判断屏幕宽度

    <script> if (screen.width < 768){....} </script>

  10. SQLServer更新语句要注意

    在SQLServer中 update语句中对于表不能使用别名 eg:update table a set a.column="" where ... 这样在SQLServer中是不 ...