配置WebSocket实现简易聊天室
添加相应依赖
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
websocket配置类
package com.example.webSocket;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
/**
* @author yanzt
* @date 2018/7/3 15:48
* @description webSocket配置类 ,注册一个 WebSocketHandlers --- WebSocketServer
*/
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new WebSocketServer(),"/webSocketServer/*");
}
}
webSocket处理类
package com.example.webSocket;
import com.example.utils.DateUtil;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.net.URLDecoder;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author yanzt
* @date 2018/7/3 15:38
* @description WebSocket 处理类
* 整合 WebSocket
*/
public class WebSocketServer extends TextWebSocketHandler {
private static final Map<WebSocketSession,String> connections = new ConcurrentHashMap<>();
/**
* 建立连接
* */
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
super.afterConnectionEstablished(session);
String uri = session.getUri().toString();
String name = uri.substring(uri.lastIndexOf("/") + 1);
String nickname = URLDecoder.decode(name,"UTF-8");
connections.put(session,nickname);
String message = String.format("* %s %s", nickname, "加入聊天!");
broadcast(new TextMessage(message));
}
/**
* 断开连接
* */
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
super.afterConnectionClosed(session, status);
String nickname = connections.remove(session);
String message = String.format("* %s %s", nickname, "退出聊天!");
broadcast(new TextMessage(message));
}
/**
* 处理消息
* */
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
String msg = "【" + connections.get(session) + "】" + DateUtil.TIME_FORMAT.format(new Date()) + " : " + message.getPayload();
broadcast(new TextMessage(msg));
}
private static void broadcast(TextMessage message){
for (WebSocketSession session:connections.keySet()){
try {
session.sendMessage(message);
} catch (Exception e) {
connections.remove(session);
try {
session.close();
} catch (Exception e2) {
e2.printStackTrace();
}
String msg = String.format("* %s %s", connections.get(session), "断开连接");
broadcast(new TextMessage(msg));
}
}
}
}
配置路由映射
@Configuration
public class MyMvcConfig implements WebMvcConfigurer{
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// 等价于<mvc:view-controller path="/success" view-name="success"/>
registry.addViewController("/success").setViewName("success");
registry.addViewController("/i18n").setViewName("i18n");
registry.addViewController("/dashboard").setViewName("dashboard");
registry.addViewController("/login").setViewName("login");
registry.addViewController("webSocket").setViewName("/webSocket/webSocket");
}
}
建立前端页面
<!DOCTYPE html>
<html>
<head lang="zh">
<meta charset="UTF-8">
<link rel="stylesheet" href="../asserts/css/bootstrap.min.css">
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet">
<script src="../asserts/js/jquery-3.2.1.slim.min.js"></script>
<script src="../asserts/js/bootstrap.min.js"></script>
<style type="text/css">
#msg {
height: 400px;
overflow-y: auto;
}
#userName {
width: 200px;
}
#logout {
display: none;
}
</style>
<title>webSocket测试</title>
</head>
<body>
<div class="container">
<div class="page-header" id="tou">webSocket及时聊天Demo程序</div>
<p class="text-right" id="logout">
<button class="btn btn-danger" id="logout-btn">退出</button>
</p>
<div class="well" id="msg"></div>
<div class="col-lg">
<div class="input-group">
<input type="text" class="form-control" placeholder="发送信息..." id="message"> <span class="input-group-btn">
<button class="btn btn-default" type="button" id="send"
disabled="disabled">发送</button>
</span>
</div>
<div class="input-group">
<input id="userName" type="text" class="form-control" name="userName" placeholder="输入您的用户名" />
<button class="btn btn-default" type="button" id="connection-btn">建立连接</button>
</div>
<!-- /input-group -->
</div>
<!-- /.col-lg-6 -->
</div>
<!-- /.row -->
</div>
<script type="text/javascript">
$(function() {
var websocket;
$("#connection-btn").bind("click", function() {
var userName = $("#userName").val();
if (userName == null || userName == "") {
alert("请输入您的用户名");
return;
}
connection(userName);
});
function connection(userName) {
var host = window.location.host;
if ('WebSocket' in window) {
websocket = new WebSocket("ws://" + host +
"/webSocketServer/" + userName);
} else if ('MozWebSocket' in window) {
websocket = new MozWebSocket("ws://" + host +
"/webSocketServer/" + userName);
}
websocket.onopen = function(evnt) {
$("#tou").html("链接服务器成功!")
$("#send").prop("disabled", "");
$("#connection-btn").prop("disabled", "disabled");
$("#logout").show();
};
websocket.onmessage = function(evnt) {
$("#msg").html($("#msg").html() + "<br/>" + evnt.data);
};
websocket.onerror = function(evnt) {
$("#tou").html("报错!")
};
websocket.onclose = function(evnt) {
$("#tou").html("与服务器断开了链接!");
$("#send").prop("disabled", "disabled");
$("#connection-btn").prop("disabled", "");
$("#logout").hide();
}
}
function send() {
if (websocket != null) {
var $message = $("#message");
var data = $message.val();
if (data == null || data == "") {
return;
}
websocket.send(data);
$message.val("");
} else {
alert('未与服务器链接.');
}
}
$('#send').bind('click', function() {
send();
});
$(document).on("keypress", function(event) {
if (event.keyCode == "13") {
send();
}
});
$("#logout-btn").on("click", function() {
websocket.close(); //关闭TCP连接
});
});
</script>
</body>
</html>