本文主要是介绍webSocket入门小案例(搭建实时交互的群聊+点对点的交流),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、简介
WebSocket是一种在单个TCP连接上进行全双工通信的协议。WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。
二、添加依赖
<!--websocket--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency><!--前端框架sockjs-client--><dependency><groupId>org.webjars</groupId><artifactId>sockjs-client</artifactId><version>1.1.2</version></dependency><!--前端框架jquery--><dependency><groupId>org.webjars</groupId><artifactId>jquery</artifactId><version>3.4.1</version></dependency><!--前端框架stomp-websocket--><dependency><groupId>org.webjars</groupId><artifactId>stomp-websocket</artifactId><version>2.3.3</version></dependency><dependency><groupId>org.webjars</groupId><artifactId>webjars-locator-core</artifactId></dependency><!--点对点通信需要用到的依赖 主要是为了获取安全登录的用户信息--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency>
三、创建websocketConfig文件
@Configuration
@EnableWebSocketMessageBroker //启动websocket消息代理
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {@Override public void configureMessageBroker(MessageBrokerRegistry registry) {//注册代理对象 /topic 用于群聊广播 ; /user 用于点对点用户通信registry.enableSimpleBroker("/topic","/user"); //全局客户端使用的前缀registry.setApplicationDestinationPrefixes("/app");//点对点使用的前缀 无需配置 默认/user//registry.setUserDestinationPrefix("/user");}//注册stomp端点@Overridepublic void registerStompEndpoints(StompEndpointRegistry registry) {//允许使用socketJs方式访问 即可通过http://IP:PORT/chat来和服务端websocket连接registry.addEndpoint("/chat").setAllowedOrigins("*").withSockJS();}
}
配置SecurityConfig
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {@BeanPasswordEncoder passwordEncoder() {return NoOpPasswordEncoder.getInstance();}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("java").password("123").roles("admin").and().withUser("four").password("123").roles("user");}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().formLogin().permitAll();}
}
三、创建接受数据的实体类
Message:群聊中消息的封装;广播的内容为什么用户发送了什么内容
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;}
}
Chat:点对点用户的通信
public class Chat {private String from; //发送消息的用户private String content; //消息的内容private String to; // 接收消息的用户public String getFrom() {return from;}public void setFrom(String from) {this.from = from;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}public String getTo() {return to;}public void setTo(String to) {this.to = to;}
}
四、controller
简单说一下Principal principal这个类 在spring security 的环境下登录后 用户的认证信息会由框架自动封装在Principal中
@Controller
public class GreetingController {@AutowiredSimpMessagingTemplate simpMessagingTemplate;
// @MessageMapping("/hello")
// @SendTo("/topic/greetings")
// public Message greeting(Message message) {
// return message;
// }//群聊广播的接口@MessageMapping("/hello")public void greeting(Message message) {simpMessagingTemplate.convertAndSend("/topic/greetings", message);}//单聊的接口@MessageMapping("/chat")public void chat(Principal principal, Chat chat) {chat.setFrom(principal.getName());simpMessagingTemplate.convertAndSendToUser(chat.getTo(), "/user/chat", chat);}
}
五、前端简易页面实现
群聊:
<!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>
</head>
<body><table><tr><td>请输入用户名</td><td><input type="text" id="name"></td></tr><tr><td><input type="button" id="connect" value="连接"></td><td><input type="button" id="disconnect" disabled="disabled" value="断开连接"></td></tr>
</table>
<div id="chat" style="display: none"><table><tr><td>请输入聊天内容</td><td><input type="text" id="content"></td><td><input type="button" id="send" value="发送"></td></tr></table><div id="conversation">群聊进行中...</div>
</div>
<script>$(function () {$("#connect").click(function () {connect();})$("#disconnect").click(function () {if (stompClient != null) {stompClient.disconnect();}setConnected(false);})$("#send").click(function () {stompClient.send('/app/hello',{},JSON.stringify({'name':$("#name").val(),'content':$("#content").val()}))})})var stompClient = null;function connect() {if (!$("#name").val()) {return;}var socket = new SockJS('/chat');stompClient = Stomp.over(socket);stompClient.connect({}, function (success) {setConnected(true);stompClient.subscribe('/topic/greetings', function (msg) {showGreeting(JSON.parse(msg.body));});})}function showGreeting(msg) {$("#conversation").append('<div>' + msg.name + ':' + msg.content + '</div>');}function setConnected(flag) {$("#connect").prop("disabled", flag);$("#disconnect").prop("disabled", !flag);if (flag) {$("#chat").show();} else {$("#chat").hide();}}
</script>
</body>
</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>
</head>
<body>
<input type="button" id="connect" value="连接">
<input type="button" id="disconnect" disabled="disabled" value="断开连接">
<hr>
消息内容:<input type="text" id="content">目标用户:<input type="text" id="to"><input type="button" value="发送" id="send">
<div id="conversation"></div>
<script>$(function () {$("#connect").click(function () {connect();})$("#disconnect").click(function () {if (stompClient != null) {stompClient.disconnect();}setConnected(false);})$("#send").click(function () {stompClient.send('/app/chat', {}, JSON.stringify({'to': $("#to").val(),'content': $("#content").val()}))})})var stompClient = null;function connect() {var socket = new SockJS('/chat');stompClient = Stomp.over(socket);stompClient.connect({}, function (success) {setConnected(true);stompClient.subscribe('/user/chat', function (msg) {showGreeting(JSON.parse(msg.body));});})}function showGreeting(msg) {$("#conversation").append('<div>' + msg.from + ':' + msg.content + '</div>');}function setConnected(flag) {$("#connect").prop("disabled", flag);$("#disconnect").prop("disabled", !flag);if (flag) {$("#chat").show();} else {$("#chat").hide();}}
</script>
</body>
</html>
这篇关于webSocket入门小案例(搭建实时交互的群聊+点对点的交流)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!