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. Spring中映射Mongodb中注解的解释

    spring-data-mongodb中的实体映射是通过MongoMappingConverter这个类实现的.它可以通过注释把java类转换为mongodb的文档. 它有以下几种注释: @Id - ...

  2. git reset soft,hard,mixed之区别深解

    GIT reset命令,似乎让人很迷惑,以至于误解,误用.但是事实上不应该如此难以理解,只要你理解到这个命令究竟在干什么. 首先我们来看几个术语 HEAD 这是当前分支版本顶端的别名,也就是在当前分支 ...

  3. Apriori原理与实践

    Apriori: 其核心思想是通过候选集生成和情节的向下封闭检测两个阶段来挖掘频繁项集.经典的关联规则数据挖掘算法Apriori 算法广泛应用于各种领域,通过对数据的关联性进行了分析和挖掘,挖掘出的这 ...

  4. display:inline 和display:inline-block和display:block的区别

    之前讲过块级元素使用display:block 行内元素使用display:inline 那么今天我们就来区分一下display:inline,display:inline-block和display ...

  5. 字符串与Objec之间互相转换

    字符串与Objec之间互相转换可通过json实现. JSON.parse(str);// 字符串转Json Object JSON.stringify(obj);// Obj转字符串

  6. c#连接各种数据库

    1.C#连接连接Access程序代码: ------------------------------------------------------------------------------- ...

  7. 关于win2008r2上配置iis,出现加密代码与联邦基础加密冲突的问题的解决

    在win2008r2上配置asp.net网站时,出现这个问题: This implementation is not part of the Windows Platform FIPS validat ...

  8. .htaccess语法中RewriteCond和RewriteRule意义

    今天看了301重定向设置的方法,对网站的首页权重有较重要意义.于是看了别人写的.htaccess文件发现一头雾水,于是查了一些资料来进一步理解. RewriteCond语法 RewriteCond T ...

  9. PHP 每天的总结(1)

    今天写博客的心情比以往还要糟糕,因为........................(完结). 1.获取某输入框的值,有两中获取方式,GET和POST .前者  没有为顾客的账户安全着想.而后者返之: ...

  10. Zabbix汉化方法

    1.windows下选择一个汉化字体包 2.拷贝到linux字体目录下 [root@www Desktop]# cd /var/www/html/zabbix/fonts/[root@www font ...