WebSocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通讯——容许服务器主动发送信息给客户端。javascript
本文档主要介绍了如何在SpringBoot中使用WebSocket。html
经过观看https://my.oschina.net/sdlvzg/blog/1154281建立项目,再执行如下操做:java
修改springboot版本,建立项目时使用的版本为1.4.1.RELEASE,更改成1.5.8.RELEASEweb
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.8.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent>
引入相关Jar包spring
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
若是是使用springboot内置tomcat进行部署的话,javaee-api这个Jar包是不须要引入的,若是是使用war包方式到tomcat中进行部署,应该还需添加一下这个包,由于这里面带有javaee对websocket支持的标准规范(jsr356)的注解。主要是@ServerEndpoint。api
package org.lvgang; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter aaaserverEndpointExporter() { return new ServerEndpointExporter(); } }
首先要注入ServerEndpointExporter,这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint。要注意,若是使用独立的servlet容器,而不是直接使用springboot的内置容器,就不要注入ServerEndpointExporter,由于它将由容器本身提供和管理。浏览器
package org.lvgang; 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; /** * websocket类 * @author Administrator * */ @ServerEndpoint(value = "/websocket") @Component public class MyWebSocket { //静态变量,用来记录当前在线链接数。应该把它设计成线程安全的。 private static int onlineCount = 0; //concurrent包的线程安全Set,用来存放每一个客户端对应的MyWebSocket对象。 private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>(); //与某个客户端的链接会话,须要经过它来给客户端发送数据 private Session session; /** * 在客户初次链接时触发, * 这里会为客户端建立一个session,这个session并非咱们所熟悉的httpsession * @param session */ @OnOpen public void onOpen(Session session) { this.session = session; webSocketSet.add(this); //加入set中 addOnlineCount(); //在线数加1 System.out.println("有新链接加入!当前在线人数为" + getOnlineCount()); try { sendMessage("当前人数为:"+getOnlineCount()); } catch (IOException e) { System.out.println("IO异常"); } } /** * 在客户端与服务器端断开链接时触发。 */ @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 (MyWebSocket item : webSocketSet) { try { item.sendMessage(message); } catch (IOException e) { e.printStackTrace(); } } } /** * 发生错误时调用此方法 * @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); } /** * 群发消息,给全部人 * @param message 消息内容 * @throws IOException */ public static void sendInfo(String message) throws IOException { for (MyWebSocket item : webSocketSet) { try { item.sendMessage(message); } catch (IOException e) { continue; } } } /** * 获得当前联接人数 * @return */ public static synchronized int getOnlineCount() { return onlineCount; } /** * 增长联接人数 */ public static synchronized void addOnlineCount() { MyWebSocket.onlineCount++; } /** * 减小联接人数 */ public static synchronized void subOnlineCount() { MyWebSocket.onlineCount--; } }
<!DOCTYPE HTML> <html> <head> <title>My WebSocket</title> </head> <body> Welcome<br/> <input id="text" type="text" /><button onclick="send()">Send</button> <button onclick="closeWebSocket()">Close</button> <div id="message"> </div> </body> <script type="text/javascript"> var websocket = null; //判断当前浏览器是否支持WebSocket if('WebSocket' in window){ websocket = new WebSocket("ws://localhost:8080/websocket"); } else{ alert('Not support websocket') } //链接发生错误的回调方法 websocket.onerror = function(){ setMessageInnerHTML("error"); }; //链接成功创建的回调方法 websocket.onopen = function(event){ setMessageInnerHTML("open"); } //接收到消息的回调方法 websocket.onmessage = function(event){ setMessageInnerHTML(event.data); } //链接关闭的回调方法 websocket.onclose = function(){ setMessageInnerHTML("close"); } //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket链接,防止链接还没断开就关闭窗口,server端会抛异常。 window.onbeforeunload = function(){ websocket.close(); } //将消息显示在网页上 function setMessageInnerHTML(innerHTML){ document.getElementById('message').innerHTML += innerHTML + '<br/>'; } //关闭链接 function closeWebSocket(){ websocket.close(); } //发送消息 function send(){ var message = document.getElementById('text').value; websocket.send(message); } </script> </html>
先经过springboot启动后台接口程序。再左击分别在两个浏览器中打开HTML测试页面,展现以下画面:tomcat
在两个页面的输入框中分别输入“我是1号”,“我是2号”两个内容,并点击“Send”,展现以下:安全
查看后台控制台也打印了相应的内容,展现以下图:springboot