springboot+websocket开发简单的在线群聊聊天web版本!近期在测试websocket插件的群聊功能。下面是一个简单的demo。分享给大家,亲测可以使用的。
1:首先是一个chat.html页面。代码如下:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>群聊</title><script src="/webjars/jquery/jquery.min.js"></script><script src="/webjars/sockjs-client/sockjs.min.js"></script><script src="/webjars/stomp-websocket/stomp.min.js"></script><script src="/app.js"></script>
</head>
<body>
<div><label for="name">请输入用户名:</label><input type="text" id="name" placeholder="用户名">
</div>
<div><button type="button" id="connect">链接</button><button type="button" disabled="disabled" id="disconnect">断开链接</button>
</div>
<div id="chat" style="display: none;"></div>
<div><label for="name">请输入聊天内容:</label><input type="text" id="content" placeholder="聊天内容">
</div>
<button type="button" id="send">发送消息</button>
<div id="greetings"><div id="conversation" style="display: none;">群聊进行中...</div>
</div>
</body>
</html>
2:其次是,关于springboot项目的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 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.8</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>socketdemo</artifactId><version>0.0.1-SNAPSHOT</version><name>socketdemo</name><description>socketdemo</description><properties><java.version>8</java.version></properties><dependencies><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.webjars</groupId><artifactId>webjars-locator-core</artifactId></dependency><dependency><groupId>org.webjars</groupId><artifactId>sockjs-client</artifactId><version>1.1.2</version></dependency><dependency><groupId>org.webjars</groupId><artifactId>stomp-websocket</artifactId><version>2.3.3</version></dependency><dependency><groupId>org.webjars</groupId><artifactId>jquery</artifactId><version>3.3.1</version></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>
3:再次是关于处理响应信息的控制器和配置类文件,以及封装消息的实体类。
配置类信息:
package com.example.socketdemo.config;import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {@Overridepublic void configureMessageBroker(MessageBrokerRegistry config){//开启websocket消息代理config.enableSimpleBroker("/topic");//设置一个目的地址前缀为app的路径信息//通过这些前缀过滤出需要被注解方法处理的消息,//例如:前缀为“/app”的可以通过@MessageMapping注解的方法处理config.setApplicationDestinationPrefixes("/app");}@Overridepublic void registerStompEndpoints(StompEndpointRegistry registry){//开启sockjs支持,解决浏览器对websocket的兼容问题registry.addEndpoint("/chat").withSockJS();}
}
处理消息响应的控制器信息:
package com.example.socketdemo.controller;import com.example.socketdemo.bean.Message;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;@Controller
public class GreetingController {@MessageMapping("/hello")@SendTo("/topic/greetings")public Message greeting(Message message) throws Exception{return message;}
}
封装消息的实体类:
package com.example.socketdemo.bean;public class Message {private String name;private String content;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}
}
4:
如图,里面就2个简单的文件,一个app.js
一个简单的静态页面。
5:app.js代码如下:
var stompClient = null;
function setConnected(connected){$("#connect").prop("disabled",connected);$("#disconnect").prop("disabled",!connected);if(connected){$("#conversation").show();$("#chat").show();}else{$("#conversation").hide();$("#chat").hide();}$("#greetings").html("");
}
function connect(){if(!$("#name").val()){return;}var socket = new SockJS('/chat');stompClient = Stomp.over(socket);stompClient.connect({},function (frame){setConnected(true);stompClient.subscribe('/topic/greetings',function (greeting){showGreeting(JSON.parse(greeting.body));});});
}
function disconnect(){if(stompClient !== null){stompClient.disconnect();}setConnected(false);
}function sendName(){stompClient.send("/app/hello",{},JSON.stringify({'name':$("#name").val(),'content':$("#content").val()}));}function showGreeting(message){$("#greetings").append("<div>"+message.name+":"+message.content+"</div>");
}
$(function (){$("#connect").click(function (){connect();});$("#disconnect").click(function (){disconnect();});$("#send").click(function (){sendName();});})
开启服务器!亲测效果如下所示:
2个浏览器!分别意味着(2个链接用户进入了该通信流程);
我使用的是搜狗浏览器一个!微软的Edge浏览器一个!
进行互动交流的测试:
这个图片是来自微软浏览器的截图。
下面的图片是来自搜狗的截图:
因为是简单的demo。所以传递的消息内容很简单。
就是一个用户名+消息内容。
大家可以拿去,自己测试代码!
欢迎大家交流互动!
代码都是我手工录入的,很累。麻烦喜欢的朋友们,给点赞一下。谢谢。