目录结构:
pom.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.segmentfault</groupId>
<artifactId>spring-boot-lesson-13</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-boot-lesson-13</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</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-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
chat.html页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>聊天室</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" ></script>
</head>
<body>
聊天消息内容:
<br/>
<textarea id="text_chat_content" readonly="readonly" cols="100" rows="9">
</textarea>
<br/>
用户:<input id="in_user_name" value=""/>
<button id="btn_join">加入聊天室</button>
<button id="btn_exit">离开聊天室</button>
<br/>
输入框:<input id="in_msg" value=""/><button id="btn_send">发送消息</button>
<script type="text/javascript">
$(document).ready(function(){
var urlPrefix ='ws://192.168.0.3:8080/chat-room/';
var ws = null;
$('#btn_join').click(function(){
var username = $('#in_user_name').val();
var url = urlPrefix+username;
ws = new WebSocket(url);
ws.onmessage = function(event){
//服务端发送的消息
$('#text_chat_content').append(event.data+'\n');
}
ws.onclose = function(event){
$('#text_chat_content').append('用户['+username+'] 已经离开聊天室!');
}
});
//客户端发送消息到服务器
$('#btn_send').click(function(){
var msg = $('#in_msg').val();
if(ws){
ws.send(msg);
}
});
//离开聊天室
$('#btn_exit').click(function(){
if(ws){
ws.close();
}
});
})
</script>
</body>
</html>
package com.segmentfault.springbootlesson13.websocket;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* 聊天室 {@link ServerEndpoint}
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
* @see
* @since 2017.08.16
*/
@ServerEndpoint("/chat-room/{username}")
public class ChatRoomServerEndpoint {
private static Map<String, Session> livingSessions = new ConcurrentHashMap<String, Session>();
@OnOpen
public void openSession(@PathParam("username") String username, Session session) {
String sessionId = session.getId();
livingSessions.put(sessionId, session);
sendTextAll("欢迎用户[" + username + "] 来到聊天室!");
// sendText(session, "欢迎用户[" + username + "] 来到聊天室!");
}
@OnMessage
public void onMessage(@PathParam("username") String username, Session session, String message) {
// sendText(session, "用户[" + username + "] : " + message);
sendTextAll("用户[" + username + "] : " + message);
}
private void sendTextAll(String message) {
livingSessions.forEach((sessionId, session) -> {
sendText(session,message);
});
}
@OnClose
public void onClose(@PathParam("username") String username, Session session) {
String sessionId = session.getId();
//当前的Session 移除
livingSessions.remove(sessionId);
//并且通知其他人当前用户已经离开聊天室了
sendTextAll("用户[" + username + "] 已经离开聊天室了!");
}
private void sendText(Session session, String message) {
RemoteEndpoint.Basic basic = session.getBasicRemote();
try {
basic.sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.segmentfault.springbootlesson13;
import com.segmentfault.springbootlesson13.websocket.ChatRoomServerEndpoint;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@SpringBootApplication
@EnableWebSocket
public class SpringBootLesson13Application {
public static void main(String[] args) {
SpringApplication.run(SpringBootLesson13Application.class, args);
}
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
@Bean
public ChatRoomServerEndpoint chatRoomServerEndpoint() {
return new ChatRoomServerEndpoint();
}
}
测试:http://192.168.0.3:8080/chat.html