初识WebSocket协议
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.服务器端
- IIS 7.0+
- Tomcat 7.0.5+
- Jetty t.0+
- WebLogic 12c
- WebSphere 8.0+
2.浏览器端
- Chrome 4+
- FireFox 5+
- IE 10+
- Safari IOS 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协议的更多相关文章
- WebSocket协议详解及应用
WebSocket协议详解及应用(七)-WebSocket协议关闭帧 本篇介绍WebSocket协议的关闭帧,包括客户端及服务器如何发送并处理关闭帧.关闭帧错误码及错误处理方法.本篇内容主要翻译自RF ...
- Websocket 协议解析
WebSocket protocol 是HTML5一种新的协议.它是实现了浏览器与服务器全双工通信(full-duplex). 现 很多网站为了实现即时通讯,所用的技术都是轮询(po ...
- 一步一步学WebSocket (一) 初识WebSocket
众所周知,Http协议是无状态的,并且是基于Request/Response的方式与服务器进行交互,也就是我们常说的单工模式.但是随着互联网的发展,浏览器与服务端进行双向通信需求的增加,长轮询向服务器 ...
- WebSocket协议开发
一直以来,网络在很大程度上都是围绕着HTTP的请求/响应模式而构建的.客户端加载一个网页,然后直到用户点击下一页之前,什么都不会发生.在2005年左右,Ajax开始让网络变得更加动态了.但所有的HTT ...
- 初识WebSocket
众所周知,Http协议是无状态的,并且是基于Request/Response的方式与服务器进行交互,也就是我们常说的单工模式.但是随着互联 网的发展,浏览器与服务端进行双向通信需求的增加,长轮询向服务 ...
- Websocket协议的学习、调研和实现
本文章同时发在 cpper.info. 1. websocket是什么 Websocket是html5提出的一个协议规范,参考rfc6455. websocket约定了一个通信的规范,通过一个握手的机 ...
- 初识HTTP协议
本篇文章从概念上初识HTTP协议,参考链接:http://www.runoob.com/http/http-tutorial.html 目录: 一.HTTP协议 HTTP 工作原理 HTT ...
- python测试基于websocket协议的即时通讯接口
随着html5的广泛应用,基于websocket协议的即时通讯有了越来越多的使用场景,本文使用python中的websocket-client模块来做相关的接口测试 import webclient ...
- Websocket协议之php实现
前面学习了HTML5中websocket的握手协议.打开和关闭连接等基础内容,最近用php实现了与浏览器websocket的双向通信.在学习概念的时候觉得看懂了的内容,真正在实践过程中还是会遇到各种问 ...
随机推荐
- iOS开发 百度坐标转火星坐标
- (CLLocationCoordinate2D)hhTrans_GCGPS:(CLLocationCoordinate2D)baiduGps { const double x_pi = 3.141 ...
- CSS实现垂直居中
Hack技术就可以啊!所以在这里我还要啰嗦两句,CSS中的确是有vertical-align属性,但是它只对(X)HTML元素中拥有valign特性的元素才生效,例如表格元素中的<td>. ...
- CentOS 6 使用 yum 安装MongoDB及服务器端配置
安装MongoDB的方法有很多种,可以源代码安装,在Centos也可以用yum源安装的方法.由于MongoDB更新得比较快,我比较喜欢用yum源安装的方法.64位Centos下的安装步骤如下: 1.准 ...
- Find a point on a 'line' between two Vector3
Find a point on a 'line' between two Vector3http://forum.unity3d.com/threads/find-a-point-on-a-line- ...
- 【Jenkins】Windows下安装&访问jenkins
1. 下载jenkins.war包 下载地址:http://jenkins-ci.org/ 2. 之后在cmd里启动jenkins,命令如下: java -jar (放置war包路径,最好没有中文)j ...
- “不支持一个STA线程上针对多个句柄的WaitAll。”的解决方案
一.异常提示 不支持一个 STA 线程上针对多个句柄的 WaitAll. 出错界面如下图: 二.解决方法 先直接上解决方案吧.其实解决方法很简单如下面的代码直接把main函数的[STAThread]属 ...
- VS2010 添加服务引用以后点不出引用服务的命名空间
声明:本次我遇到的仅是这类情况中的其中一个个例,不要拘泥于些噢! 问题描述: 1.我建了一个新项目,不引用服务前是好的,可以打点点出任何已有有命名空间,但是引用服务以后就是点不出服务的命名空间. 2. ...
- 点击空白处隐藏div-阻止事件冒泡
$(" body").click(function(){ $("#div").hide(); }); $("button").click(f ...
- python打印目录下的文件名
打印当前目录所有文件名 import fnmatch, os def allFiles(root, patterns = '*', single_level = False, yield_folder ...
- 爱壁纸 站立会议(六)--Spring阶段总结会议
爱壁纸 站立会议(六)--Spring阶段总结会议 一.会议时间 2014年4月15日 星期三 21:00-21:20 今天是spring阶段最后一天,大家都对这一星期的任务概况做出了总结所以时间稍微 ...