简单说明
1.两种方式,一种使用tomcat的websocket实现,一种使用spring的websocket
2.tomcat的方式需要tomcat 7.x,JEE7的支持。
3.spring与websocket整合需要spring 4.x,并且使用了socketjs,对不支持websocket的浏览器可以模拟websocket使用
方式一:tomcat
使用这种方式无需别的任何配置,只需服务端一个处理类,
服务器端代码
package com.hc.config;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
/**
* @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
* 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
* @Component注解告诉SpringMVC该类是一个SpringIOC容器下管理的类
*/
@ServerEndpoint(value = "/websocket")
@Component
public class WebSocketTest {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
private static CopyOnWriteArraySet<WebSocketTest> webSocketSet = new CopyOnWriteArraySet<WebSocketTest>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
private Timer timer = null;
private static final Random random = new Random();
/**
* 连接建立成功调用的方法
* @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
@OnOpen
public void onOpen(Session session){
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在线数加1
try {
if (session.isOpen()) {
//设置心跳发送信息。每2秒发送一次信息。
//timer = new Timer(true);
//timer.schedule(task, 1000, 2000);
} } catch (Exception e) {
try {
session.close();
} catch (IOException e1) {
}
}
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(WebSocketTest 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);//异步发送消息
}
/**
* 心跳任务。发送随机数。
*/
TimerTask task = new TimerTask() {
public void run() {
long param = random.nextInt(100);
sendLong(param);
}
};
/**
* 发送心跳信息
*/
public void sendLong(long param) {
try {
if (session.isOpen()) {
this.session.getBasicRemote().sendText(String.valueOf(param));
}
} catch (IOException e) {
try {
this.session.close();
} catch (IOException e1) {}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketTest.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketTest.onlineCount--;
}
}
配置文件
package com.hc.config;
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 serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
pom依赖
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<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>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
客户端js
<%@ page language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Java后端WebSocket的Tomcat实现</title>
</head>
<body>
Welcome<br/><input id="text" type="text"/>
<button onclick="send()">发送消息</button>
<hr/>
<button onclick="closeWebSocket()">关闭WebSocket连接</button>
<hr/>
<div id="message"></div>
</body>
<script type="text/javascript">
var websocket = null;
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8080/websocket");
//websocket = new WebSocket("ws://localhost:8080/JavaWebSocket/websocket");
}
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>
发送消息只需要使用websocket.send(“发送消息”),就可以触发服务端的onMessage()方法,当连接时,触发服务器端onOpen()方法,此时也可以调用发送消息的方法去发送消息。关闭websocket时,触发服务器端onclose()方法,此时也可以发送消息,但是不能发送给自己,因为自己的已经关闭了连接,但是可以发送给其他人
方法二:spring整合
此方式基于spring mvc框架,相关配置可以看我的相关博客文章
服务端代码
WebSocketStompConfig…java
这个类是配置类,所以需要在spring mvc配置文件中加入对这个类的扫描,第一个addHandler是对正常连接的配置
package com.hc.config;
import java.security.Principal;
import java.util.Map;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;
@Configuration
@EnableWebSocketMessageBroker//开启STOMP协议来传输基于代理(message broker)的消息,这时控制器支持@MessageMapping
public class WebSocketStompConfig extends AbstractWebSocketMessageBrokerConfigurer{
//注册STOMP协议的节点(endpoint),并映射指定的URL
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/stomp")//指定使用SocketJS协议
.setHandshakeHandler(new DefaultHandshakeHandler() {
@Override
protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes) {
//将客户端标识封装为Principal对象,从而让服务端能通过getName()方法找到指定客户端
Object o = attributes.get("name");
return new FastPrincipal(o.toString());
}
})
//添加socket拦截器,用于从请求中获取客户端标识参数
.addInterceptors(new HandleShakeInterceptors()).setAllowedOrigins("*").withSockJS();
}
//配置消息代理
public void configureMessageBroker(MessageBrokerRegistry registry) {
//客户端发送消息的请求前缀
//registry.setApplicationDestinationPrefixes("/app");
//客户端订阅消息的请求前缀,topic一般用于广播推送,queue用于点对点推送
registry.enableSimpleBroker("/topic", "/queue");
//服务端通知客户端的前缀,可以不设置,默认为user
registry.setUserDestinationPrefix("/user");
/* 如果是用自己的消息中间件,则按照下面的去配置,删除上面的配置
* registry.enableStompBrokerRelay("/topic", "/queue")
.setRelayHost("rabbit.someotherserver")
.setRelayPort(62623)
.setClientLogin("marcopolo")
.setClientPasscode("letmein01");
registry.setApplicationDestinationPrefixes("/app", "/foo");
* */
}
//定义一个自己的权限验证类
class FastPrincipal implements Principal {
private final String name;
public FastPrincipal(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
}
HandleShakeInterceptors.java
这个类的作用就是在连接成功前和成功后增加一些额外的功能,用户验证连接是否合法,这里只是做了简单的处理,具体可根据具体的业务去改写
package com.hc.config;
import java.util.Map;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
/**
* 检查握手请求和响应, 对WebSocketHandler传递属性
*/
public class HandleShakeInterceptors implements HandshakeInterceptor {
/**
* 在握手之前执行该方法, 继续握手返回true, 中断握手返回false.
* 通过attributes参数设置WebSocketSession的属性
*
* @param request
* @param response
* @param wsHandler
* @param attributes
* @return
* @throws Exception
*/
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
String name= ((ServletServerHttpRequest) request).getServletRequest().getParameter("name");
System.out.println("======================握手前" + name);
//保存客户端标识
attributes.put("name", "8888");
return true;
}
/**
* 在握手之后执行该方法. 无论是否握手成功都指明了响应状态码和相应头.
*
* @param request
* @param response
* @param wsHandler
* @param exception
*/
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
WebSocketHandler wsHandler, Exception exception) {
String name= ((ServletServerHttpRequest) request).getServletRequest().getParameter("name");
System.out.println("======================握手后" + name);
}
}
在controller层中写具体的app/拦截到url所做出的具体业务处理:
package com.hc.controller;
import java.io.UnsupportedEncodingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class StompController {
@Autowired
SimpMessagingTemplate SMT;
@MessageMapping("/topic/message")//@MessageMapping接收客户端消息
@SendTo("/topic/sub")
public String subscription(String str) throws MessagingException, UnsupportedEncodingException {
System.err.println(str);
return str;
//SMT.convertAndSend("/topic/sub","开始推送消息了:"+str);
}
/**
* 当有客户端订阅"/topic/sub",会收到消息
* @return
*/
@SubscribeMapping("/topic/sub")
public String sub() {
System.out.println("1某个用户订阅了我:");
return "success";
}
@SubscribeMapping("/user/{username}/topic/sub")
public String subtwo() {
System.out.println("2某个用户订阅了我:");
return "success";
}
@SubscribeMapping("/topic/sa")
public String sa() {
System.out.println("3某个用户订阅了我:");
return "success";
}
}
Tips:SimpMessagingTemplate这个bean是当你的配置生效后,spring自动注入的bean,直接用就可以了。它可以实现注解@sendto或者@sendtoUser的所有功能,并且可以在任意地方使用(sendto系列注解必须要在controller中陪着MassageMapp使用),用它就可以实现后台的主动推送消息。当然sendto也有它的好处,比如直接将你得pojo转json字符串发到对于的消费者那里。
pom依赖
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
到此后台代码完成,开始配置前端jsp
客户端js
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>stomp</title>
<link href="https://cdn.bootcss.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js"></script>
<script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
</head>
<body>
<noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websocket relies on Javascript being
enabled. Please enable
Javascript and reload this page!</h2></noscript>
<div id="main-content" class="container">
<div class="row">
<div class="col-md-6">
<form class="form-inline">
<div class="form-group">
<label for="connect">register an user,input name:</label>
<input type="text" id="username" class="form-control" placeholder="Your name here...">
<button id="confirm" class="btn btn-default" type="submit">confirm</button>
</div>
<div class="form-group">
<label for="connect">WebSocket connection:</label>
<button id="connect" class="btn btn-default" type="submit">Connect</button>
<button id="disconnect" class="btn btn-default" type="submit" disabled="disabled">Disconnect
</button>
</div>
</form>
</div>
<div class="col-md-6">
<form class="form-inline">
<div class="form-group">
<label for="name">What is your name?</label>
<input type="text" id="name" class="form-control" placeholder="Your name here...">
</div>
<button id="send" class="btn btn-default" type="submit">Send</button>
</form>
</div>
</div>
<div class="row">
<div class="col-md-12">
<table id="conversation" class="table table-striped">
<thead>
<tr>
<th>Greetings</th>
</tr>
</thead>
<tbody id="greetings">
</tbody>
</table>
</div>
</div>
</div>
<script type="text/javascript">
/**
*
*/
var stompClient = null;
var hostaddr = window.location.host + "<c:url value='/stomp/' />";
var url = 'ws://' + hostaddr;
console.info(url);
function setConnected(connected) {
$("#connect").prop("disabled", connected);
$("#disconnect").prop("disabled", !connected);
if (connected) {
$("#conversation").show();
}
else {
$("#conversation").hide();
}
$("#greetings").html("");
}
var username="";
function connect() {
var socket = new SockJS("stomp");// 建立连接对象(还未发起连接)
stompClient = Stomp.over(socket);// 获取 STOMP 子协议的客户端对象
stompClient.connect({}, function (frame) {// 向服务器发起websocket连接并发送CONNECT帧
setConnected(true);
console.log('连接:: ' + frame);
stompClient.subscribe('/topic/sub', function (greeting) {// 连接成功时(服务器响应 CONNECTED 帧)的回调方法
alert("got message with body :" + greeting.body);
showGreeting(greeting.body);
});
stompClient.subscribe('/user/'+username+'/topic/sub', function (greeting) {
alert("got message with body :" + greeting.body);
showGreeting(greeting.body);
});
});
}
function disconnect() {
if (stompClient !== null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
function sendName() {
stompClient.send("/topic/message", {},$("#name").val());
}
function showGreeting(message) {
$("#greetings").append("<tr><td>" + message + "</td></tr>");
}
$(function () {
$("form").on('submit', function (e) {
e.preventDefault();
});
$( "#connect" ).click(function() { connect(); });
$( "#disconnect" ).click(function() { disconnect(); });//从客户端主动断开连接
$( "#send" ).click(function() { sendName(); });
$("#confirm").click(function(){username=$("#username").val();connect();});
});
</script>
</body>
</html>
这个前端的demo也是直接从spring官网复制的,它的连接和发送方式和原生的websocket是完全不一样的,首先注意一下几点:1. 通过sockJS绑定好服务器中配置的endpoint连接点,并通过stomp.over方式创建一个stompClient,完成客户端的创建。
2.再通过stompClient.subscribe订阅N多个的消息地址。
3.发送消息的时候也同样的通过stompClient.send方法去发送消息到指定的。destination
以上例子采用的是springboot框架