1.准备
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2.配置
在有@Configuration配置文件下加上这么一句,ServerEndpointExporter 会自动扫描WebSocket相关注解
/**
* @comment 注册WebSocket
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
3.前端
<html>
<head>
<meta charset="utf-8">
<title>测试</title>
</head>
<body>
<input id="text" type="text" />
<button onclick="send()">发送消息</button>
<button onclick="closeWebSocket()">关闭连接</button>
<div id="message">
</div>
<script type="text/javascript">
var websocket = null;
//判断当前浏览器是否支持WebSocket
if('WebSocket' in window){
websocket = new WebSocket("ws://10.0.0.46:9000/bosque/ws?何佳");
}
else{
alert('Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function(){
console.log("服务器错误!");
};
//连接成功建立的回调方法
websocket.onopen = function(event){
console.log("连接成功");
}
//接收到消息的回调方法
websocket.onmessage = function(event){
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function(){
console.log("连接关闭");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭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>
</body>
</html>
4.服务端
package com.bosque.rest.websocket;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
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;
import com.bosque.rest.websocket.domain.Account;
import com.bosque.rest.websocket.domain.MyWebSocket;
@ServerEndpoint(value = "/ws")
@Component
public class MySocketApp {
//记录当前已连接用户
private static CopyOnWriteArraySet<MyWebSocket> MyWebSocketSet = new CopyOnWriteArraySet<>();
//与某个客户端的连接会话
private MyWebSocket socket;
/**
* @comment 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session) {
Account account = new Account();
String name = null;
try {
name = URLDecoder.decode(session.getQueryString(), "utf-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
account.setUsername(name);
this.socket = new MyWebSocket(account,session);
MyWebSocketSet.add(this.socket);
System.out.println("["+account.getUsername()+"]连接成功 "+getTime(new Date()));
}
/**
* @comment 连接关闭调用的方法
*/
@OnClose
public void onClose() {
MyWebSocketSet.remove(socket);
System.out.println("["+socket.getAccount().getUsername()+"]连接中断 "+getTime(new Date()));
}
/**
* @comment 接收消息
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("来自客户端的消息:" + message);
try {
sendMessage("服务端回应消息:"+message,session);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @comment 发生错误时调用
*/
@OnError
public void onError(Session session, Throwable error){
System.out.println("发生错误");
}
/**
* @throws IOException
* @comment 发送消息
*/
public void sendMessage(String message,Session session) throws IOException{
session.getBasicRemote().sendText(message);
}
public String getTime(Date date){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return format.format(date);
}
}