【springboot整合WebSocket二】点对点单聊实现

添加依赖

由于涉及到用户的概念,我们需要加入security的依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

配置security的config

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin")
                .password("$2a$10$GAF30muH14Bw2i9xXJtNFexgQxEOEbGks2QVxWWQ3181Us7IcYQDO")
                .roles("admin")
                .and()
                .withUser("sang")
                .password("$2a$10$GAF30muH14Bw2i9xXJtNFexgQxEOEbGks2QVxWWQ3181Us7IcYQDO")
                .roles("user");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .permitAll();
    }
}

webSocket的配置

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic","/queue");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/chat").withSockJS();
    }
}

前端页面

<!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="/chat.js"></script>
</head>
<body>
        <div id="chat">
            <div id="chatsContent">
            </div>
            <div>
                请输入聊天内容:
                <input type="text" id="content" placeholder="聊天内容">
                目标用户:
                <input type="text" id="to" placeholder="目标用户">
                <button id="send">发送</button>
            </div>
        </div>

</body>
</html>

前端js

var stompClient = null;
function connect() {
    var socket = new SockJS('/chat');
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function (frame) {
        stompClient.subscribe('/user/queue/chat', function (chat) {
            showGreeting(JSON.parse(chat.body));
        });
    });
}
function sendMsg() {
    stompClient.send("/app/chat", {},
        JSON.stringify({'content':$("#content").val(),
            'to':$("#to").val()}));
}
function showGreeting(message) {
    $("#chatsContent")
        .append("
" + message.from+":"+message.content + "
"
); } $(function () { connect(); $( "#send" ).click(function() { sendMsg(); }); });

结果展示

在这里插入图片描述

你可能感兴趣的:(SpirngBoot)