赞
踩
1 概述
WebSocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工通信:允许服务器主动发送信息给客户端。 WebSocket协议跟http协议并没有太多的关系,不过使用了http的握手机制.
http协议是应用很广的网络协议,它在通信前必须经过3次握手,它又分为短链接,长链接.短链接是每次请求都要三次握手才能发送自己的信息。即每一个request对应一个response。长链接是在一定的期限内保持链接。保持TCP连接不断开。客户端与服务器通信,必须要有客户端发起请求然后服务器返回结果。客户端是主动的,服务器是被动的。https是在http之上进行安全加密的协议,本质上还是http协议,通信方式还是一样.
http协议在通信时,需要不停的进行连接,关闭,这是十分耗费资源的,而且效率低下.为了解决这个问题,WebSocket协议应运而生.它只需要进行一次握手就可以打开一条通信通道,并且不需要客户端发起查询请求,当有信息时,服务器会回调客户端.
2 demo
2.1 pom.xml
如果不是使用Springboot进行开发的,需要引入javaee-api,@ServerEndpoint这个注解是Javaee标准里的注解,tomcat7以上已经对其进行了实现,如果是用传统方法使用tomcat发布项目,只要在pom文件中引入javaee标准即可使用.而Springboot使用内置的Tomcat,已经包含.
<!-- websocket,包括了配置WEB启动器 SpringMVC、Restful、jackson -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2.2 @ServerEndpoint
首先要注入ServerEndpointExporter,这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint。不然会报无法连接.要注意,如果使用独立的servlet容器,而不是直接使用springboot的内置容器,就不要注入ServerEndpointExporter,因为它将由容器自己提供和管理。
- @Configuration
- public class WebSocketConfig {
- @Bean
- public ServerEndpointExporter serverEndpointExporter() {
- return new ServerEndpointExporter();
- }
-
- }
2.3 页面
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/html">
- <head>
- <meta charset="UTF-8">
- <script src="../js/jquery-3.1.1.min.js"></script>
- <title>Java后端WebSocket实现</title>
- </head>
- <body>
- 信息框:<input id="text" type="text"/>
- <button onclick="send()">发送</button>
- <hr/>
- <button onclick="closeWebSocket()">关闭WebSocket连接</button>
- <hr/>
- 收到的信息如下:</br>
- <div id="message">
-
- </div>
- </body>
- <script type="text/javascript">
- var webSocket = null;
- //判断当前浏览器是否支持WebSocket
- if ('WebSocket' in window) {
- //需要注意URL的格式,以ws:开头的
- webSocket = new WebSocket("ws://127.0.0.1:8888/webSocket");
- }
- else {
- alert('当前浏览器不支持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();
- }
-
- //将消息显示在网页上
- var val = "";
- function setMessageInnerHTML(innerHTML) {
- var time = getCurTime();
- var temp = time+ '<br/>' + innerHTML + '<br/>';
- val = val + temp;
- $("#message").html(val);
- }
-
- //关闭WebSocket连接
- function closeWebSocket() {
- webSocket.close();
- }
-
- //发送消息
- function send() {
- var message = $('#text').val();
- webSocket.send(message);
- $("#text").val("");
- }
-
- function pad2(n) { return n < 10 ? '0' + n : n }
- function getCurTime() {
- var date = new Date();
- return date.getFullYear().toString() +"-"+ pad2(date.getMonth() + 1) +"-"+ pad2(date.getDate()) +" "+ pad2(date.getHours()) +":"+ pad2(date.getMinutes()) +":"+ pad2(date.getSeconds());
- }
- </script>
- </html>

2.4 java-websocket代码
- package com.baibeiyun.environ;
-
- 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;
-
- import org.springframework.stereotype.Component;
-
- /**
- * @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
- * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
- */
- @ServerEndpoint("/webSocket")
- @Component
- public class WebSocket {
- //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
- private static int onlineCount = 0;
-
- /**
- * concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
- * 若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
- */
- private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<>();
-
- //与某个客户端的连接会话,需要通过它来给客户端发送数据
- 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 (WebSocket item : webSocketSet) {
- try {
- item.sendMessage(message);
- } catch (IOException e) {
- e.printStackTrace();
- continue;
- }
- }
- }
-
- /**
- * 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。
- * @param message
- * @throws IOException
- */
- public void sendMessage(String message) throws IOException {
- String respMsg = null;
- if ("1".equals(message)){
- respMsg = "Java";
- }else if ("2".equals(message)){
- respMsg = "python";
- }else if ("3".equals(message)){
- respMsg = "groovy";
- }else{
- respMsg = "欢迎访问!请根据如下规则获取您想要的内容:1:java 2:python 3:groovy";
- }
- this.session.getBasicRemote().sendText(respMsg);
- //this.session.getAsyncRemote().sendText(message);
- }
-
- /**
- * 发生错误时调用
- * @param session
- * @param error
- */
- @OnError
- public void onError(Session session, Throwable error) {
- System.out.println("发生错误");
- error.printStackTrace();
- }
-
-
- public static synchronized int getOnlineCount() {
- return onlineCount;
- }
-
- public static synchronized void addOnlineCount() {
- onlineCount++;
- }
-
- public static synchronized void subOnlineCount() {
- onlineCount--;
- }
- }

------------------
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。