H5笔记-WebSocket协议
来源:互联网 发布:今晚非农数据预测 编辑:程序博客网 时间:2024/06/06 01:20
啥是websocket?
websocket是一种基于TCP协议的一种新的协议,和HTTP是并存的两者不同协议。
既然是协议,就必然像HTTP那样涉及到客户端和服务端。
目前客户端的实现比较统一,各个浏览器厂商都是遵循的W3C的H5技术来支持websocket的。
但是服务端的实现在技术提出初期,由于没有一套统一的Java API标准,各个服务器中间件(tomcat、jetty)的实现各不相同;
直到Oracle发布了基于JDK7的JSR356规范,使WebSocket的Java API得到了统一。所以只要Web容器支持JSR356,那么我们写WebSocket时,代码就都是一样的了。
Tomcat从7.0.81开始支持JSR356,但是tomcat7.X对websocket的实现,不如tomcat8.X的实现用着方便。tomcat8开发了好多标签,开发起来方便多了。jetty从9.3开始支持websocket,具体见下图:
websocket有啥作用?
(1)对于http协议,只能客户端发起请求时,服务端才响应客户端。也就是说,客户端想要要什么东西,都是客户端主动去拿。实现不了服务端主动去给。
(2)对于websocket协议,服务端和客户端的通信是双向的,客户端可以请求服务器从服务器拿数据,服务器数据更新了,也可以直接推送给客户端。websocket协议相比HTTP协议,可以高效节能的通过双向通信实现数据的实时传输。
如何使用?
开发环境要求:
JDK1.7及以上;
中间件支持JSR356规范;一般支持了JSR356规范的中间件就支持websocket;
框架的话,spring貌似4.X开始支持websocket;使用场景举例:
消息广播、在线多组讨论、 个人消息推送代码示例:
web工程下需要引入tomcat服务器里lib文件夹下的websocket-api.jar
***********************消息广播-客户端************************<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML><html> <head> <title>消息广播</title> </head> <body> <p>场景描述:消息广播</p> <input id="text" type="text"/> <button onclick="send()">发送消息</button> <button onclick="closeWebSocket()">关闭WebSocket连接</button> <hr/> <div id="message"></div> <hr/> </body> <script type="text/javascript"> var websocket = null; //判断当前浏览器是否支持WebSocket if ('WebSocket' in window) { websocket = new WebSocket("ws://localhost:9082/TestWebSocket/thunisoft/websocket1"); } else { alert('当前浏览器 Not support websocket') } //连接发生错误的回调方法 websocket.onerror = function () { setMessageInnerHTML("WebSocket连接发生错误"); }; //连接成功建立的回调方法 websocket.onopen = function () { setMessageInnerHTML("WebSocket连接成功"); } //接收到消息的回调方法 websocket.onmessage = function (event) { setMessageInnerHTML(event.data); } //连接关闭的回调方法 websocket.onclose = function () { setMessageInnerHTML("WebSocket连接关闭"); } //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。 window.onbeforeunload = function () { closeWebSocket(); } //将消息显示在网页上 function setMessageInnerHTML(innerHTML) { document.getElementById('message').innerHTML += innerHTML + '<br/>'; } //关闭WebSocket连接 function closeWebSocket() { websocket.close(); } //发送消息 function send() { var message = document.getElementById('text').value; websocket.send(message); } </script> </html>***********************消息广播-服务端************************package com.thunisoft.server;import java.io.IOException;import java.util.concurrent.CopyOnWriteArraySet;import javax.websocket.OnClose;import javax.websocket.OnError;import javax.websocket.OnMessage;import javax.websocket.OnOpen;import javax.websocket.Session;import javax.websocket.server.ServerEndpoint;/** * @Description 场景:消息广播 * @author YULQ * @date 2017-6-14 上午10:38:20 */@ServerEndpoint(value = "/thunisoft/websocket1")public class MyServer { // 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。 private static int onlineCount = 0; // concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识 private static CopyOnWriteArraySet<MyServer> webSocketSet = new CopyOnWriteArraySet<MyServer>(); // 与某个客户端的连接会话,需要通过它来给客户端发送数据 private Session session; /** * 连接建立成功调用的方法 * * @param session * 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据 */ @OnOpen public void onOpen(Session session) { this.session = session; webSocketSet.add(this); // 加入set中 addOnlineCount(); // 在线数加1 System.out.println("有新连接加入!当前在线人数为" + getOnlineCount()); } /** * 连接关闭调用的方法 */ @OnClose public void onClose() { webSocketSet.remove(this); // 从set中删除 subOnlineCount(); // 在线数减1 System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount()); } /** * 收到客户端消息后调用的方法 * * @param message * 客户端发送过来的消息 * @param session * 可选的参数 */ @OnMessage public void onMessage(String message, Session session) { System.out.println("来自客户端的消息:" + message); // 群发消息 for (MyServer item : webSocketSet) { try { item.sendMessage(message); } catch (IOException e) { e.printStackTrace(); continue; } } } /** * 发生错误时调用 * * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { System.out.println("发生错误"); error.printStackTrace(); } /** * 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。 * * @param message * @throws IOException */ public void sendMessage(String message) throws IOException { this.session.getBasicRemote().sendText(message); // this.session.getAsyncRemote().sendText(message); } public static synchronized int getOnlineCount() { return onlineCount; } public static synchronized void addOnlineCount() { MyServer.onlineCount++; } public static synchronized void subOnlineCount() { MyServer.onlineCount--; }}
***********************在线讨论组-客户端************************<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML><html> <head> <title>在线多组讨论</title> </head> <body> <p>场景描述:在线多组讨论</p> <input id="nickName" type="text" placeholder="请输入您的聊天昵称"/> <button onclick="openWebsocket('平民')">进入【平民】讨论组</button> <button onclick="openWebsocket('狼人')">进入【狼人】讨论组</button></BR></BR></BR> <input id="text" type="text"/><button onclick="send()">发送消息</button> <button onclick="closeWebSocket()">退出当前讨论组</button> <hr/></BR></BR> <div id="message"></div> </body> <script type="text/javascript"> var websocket = null; var nickName = null; function openWebsocket(selectedGroupName){ var name = document.getElementById('nickName').value; if(name == ""){ alert("请输入您的昵称!"); return; } nickName = name; document.getElementById('message').innerHTML = ""; //判断当前浏览器是否支持WebSocket if ('WebSocket' in window) { websocket = new WebSocket("ws://localhost:9082/TestWebSocket/thunisoft/websocket1/"+selectedGroupName+"/"+nickName); } else { alert('当前浏览器 Not support websocket') } //连接发生错误的回调方法 websocket.onerror = function () { setMessageInnerHTML("WebSocket连接发生错误"); }; //连接成功建立的回调方法 websocket.onopen = function () { setMessageInnerHTML("您已进入讨论组:"+selectedGroupName); } //接收到消息的回调方法 websocket.onmessage = function (event) { setMessageInnerHTML(event.data); } //连接关闭的回调方法 websocket.onclose = function () { setMessageInnerHTML("WebSocket连接关闭"); } //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。 window.onbeforeunload = function () { closeWebSocket(); } //将消息显示在网页上 function setMessageInnerHTML(innerHTML) { document.getElementById('message').innerHTML += innerHTML + '<br/>'; } //关闭WebSocket连接 function closeWebSocket() { websocket.close(); } } //发送消息 function send() { var message = document.getElementById('text').value; websocket.send(message); } </script> </html>***********************在线讨论组-服务端************************package com.thunisoft.server;import java.io.IOException;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ConcurrentMap;import java.util.concurrent.CopyOnWriteArraySet;import javax.websocket.OnClose;import javax.websocket.OnError;import javax.websocket.OnMessage;import javax.websocket.OnOpen;import javax.websocket.Session;import javax.websocket.server.PathParam;import javax.websocket.server.ServerEndpoint;/** * @Description 场景:在线多个讨论组 * @author YULQ * @date 2017-6-28 上午10:36:44 */@ServerEndpoint(value = "/thunisoft/websocket1/{groupName}/{nickName}")public class MyServerGroup { // 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。 private static int onlineCount = 0; // concurrent包的线程安全Map,用来存放各个讨论组集合。<key=讨论组名称,value=讨论组人员名称> private static ConcurrentMap<String, CopyOnWriteArraySet<MyServerGroup>> webSocketGroupap = new ConcurrentHashMap<String, CopyOnWriteArraySet<MyServerGroup>>(); // 与某个客户端的连接会话,需要通过它来给客户端发送数据 private Session session; // 讨论组名称 private String groupName; // 用户昵称 private String nickName; /** * 客户端与服务端建立链接 * * @param session * 通话session * @param groupName * 讨论组名称 * @param nickName * 用户昵称 */ @OnOpen public void onOpen(Session session, @PathParam(value = "groupName") String groupName, @PathParam(value = "nickName") String nickName) { this.session = session; this.groupName = groupName; this.nickName = nickName; // 将用户加入相应的讨论组 boolean needCreateGroup = (webSocketGroupap.get(groupName) == null); if (needCreateGroup) { CopyOnWriteArraySet<MyServerGroup> group = new CopyOnWriteArraySet<MyServerGroup>(); webSocketGroupap.put(groupName, group); } CopyOnWriteArraySet<MyServerGroup> groupOfUser = webSocketGroupap.get(groupName); groupOfUser.add(this); // 在线数加1 addOnlineCount(); System.out.println(nickName + "加入了讨论组" + groupName + "!当前在线人数为" + getOnlineCount()); } /** * 客户端关闭连接事件 * * @param groupName * @param nickName */ @OnClose public void onClose(@PathParam(value = "groupName") String groupName, @PathParam(value = "nickName") String nickName) { CopyOnWriteArraySet<MyServerGroup> groupOfUser = webSocketGroupap.get(groupName); groupOfUser.remove(this); subOnlineCount(); // 在线数减1 System.out.println(nickName + "退出了讨论组" + groupName + "!当前在线人数为" + getOnlineCount()); // 讨论组没人时,移除该讨论组 if (groupOfUser.size() == 0) { System.out.println("讨论组【" + groupName + "】被移除"); webSocketGroupap.remove(groupName); } } /** * 发生错误时调用 * * @param session * @param error */ @OnError public void onError(Session session, Throwable error, @PathParam(value = "groupName") String groupName) { System.out.println("讨论组【" + groupName + "】发生错误"); error.printStackTrace(); } @OnMessage public void onMessage(String message, Session session, @PathParam(value = "groupName") String groupName, @PathParam(value = "nickName") String nickName) { System.out.println("来自讨论组【" + groupName + "】的" + nickName + "说话了;" + message); // 针对当前讨论组,群发消息 CopyOnWriteArraySet<MyServerGroup> groupOfUser = webSocketGroupap.get(groupName); for (MyServerGroup item : groupOfUser) { try { item.sendMessage(nickName + ":" + message); } catch (IOException e) { System.out.println("发送消息失败!"); e.printStackTrace(); continue; } } } /** * 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。 * * @param message * @throws IOException */ public void sendMessage(String message) throws IOException { this.session.getBasicRemote().sendText(message); // this.session.getAsyncRemote().sendText(message); } public static synchronized int getOnlineCount() { return onlineCount; } public static synchronized void addOnlineCount() { MyServerGroup.onlineCount++; } public static synchronized void subOnlineCount() { MyServerGroup.onlineCount--; }}
@ServerEndpoint注解的configurator属性,可以自定义配置信息。客户端和服务端握手阶段,会先执行自定义的配置信息类,然后再执行open方法。
首先,自定义一个配置类:
package com.thunisoft.configurator;import java.util.Map;import javax.websocket.HandshakeResponse;import javax.websocket.server.HandshakeRequest;import javax.websocket.server.ServerEndpointConfig;import javax.websocket.server.ServerEndpointConfig.Configurator;/** * @Description 服务端配置类,对所有客户端生效 * @author YULQ * @date 2017-6-30 下午2:23:46 */public class MyConfigurator extends Configurator { @Override public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) { // TODO Auto-generated method stub Map<String, Object> configMap = sec.getUserProperties(); configMap = sec.getUserProperties(); configMap.put("config1", "config1-value"); configMap.put("config2", "config2-value"); }}
然后给服务端的注解配置这个类,在服务端的各个方法里就可以获取配置值了:
@ServerEndpoint(value = "/thunisoft/websocket1", configurator = MyConfigurator.class)public class MyServer { //服务端代码......... this.session.getUserProperties().get("config1"); //服务端代码.........}
小结
以下内容是在学习tomcat8的websocket过程中的一些知识点和注意事项,记录下来,方便日后回顾和理解。
(1)对于tomcat有三种连接器:bio连接器(默认)、nio连接器、apr连接器。虽然 WebSocket 可以和任何 HTTP 连接器一起使用,但并不建议和 bio连接器一起使用。因为 WebSocket 典型用途下,大量连接很多时候都是空闲的,而bio连接器不管连接是否空闲,每个连接都会分配一个线程。这就会导致tomcat服务器会产生大量的空闲线程,从而占用内存,浪费资源。
tomcat官网:目前,已有报告(56304)发现,Linux 会用大量时间来报告删除的连接。当利用 BIO HTTP 连接器使用 WebSocket 时,当在这段时间内写入时,就容易产生线程阻塞。建议选择nio 连接器,因为它使用的是非阻塞 IO,从而能解决这些问题。
优秀文章链接:
http://blog.csdn.net/frank_good/article/details/50856585
https://www.ibm.com/developerworks/cn/java/j-lo-WebSocket/
- H5笔记-WebSocket协议
- WebSocket协议-个人笔记
- Golang实现基于Websocket协议的H5聊天室
- Golang实现基于Websocket协议的H5聊天室(上)
- 浅析H5中的WebSocket对象,创建 一个基于node的TCP网络协议的通讯协议
- H5 websocket C# server
- H5的 WebSocket
- H5——webSocket
- websocket协议
- WebSocket协议
- WebSocket协议
- Websocket协议
- Websocket协议
- webSocket协议
- WebSocket协议
- WebSocket协议
- Websocket协议
- websocket协议
- glBindAttribLocation GLSL,generic vertex attributes)
- 严重: Exception sending context initialized event to listener instance of class org.springframework.we
- zookeeper的leader选举和最大故障节点数
- mybatis+druid的配置
- cordova学习笔记_创建一个cordova项目
- H5笔记-WebSocket协议
- 归并排序及java实现
- 开发PHP软件配置和介绍
- PLSQL Developer向Oracle导入sql文件
- android 非系统APP访问字符设备
- redis 5种数据类型及应用场景
- Hystrix 使用与分析
- Android环信换新即时聊天集成EaseUI的使用v3.0
- Linux环境下部署TestLink指导手册--2