在spring boot中使用webSocket組件(二)

該篇演示如何使用websocket建立一對一的聊天室,廢話很少說,咱們立刻開始!javascript

一.首先先建立前端頁面,代碼以下圖所示:html

1.login.html前端

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<meta charset="UTF-8" />
<head>
    <title>登錄頁面</title>
</head>
<body>
<div th:if="${param.error}">
    無效的帳號和密碼
</div>
<div th:if="${param.logout}">
    你已註銷
</div>
<form th:action="@{/login}" method="post">
    <div><label> 帳號 : <input type="text" name="username"/> </label></div>
    <div><label> 密碼: <input type="password" name="password"/> </label></div>
    <div><input type="submit" value="登錄"/></div>
</form>
</body>
</html>

2.chat.htmljava

<!DOCTYPE html>

<html xmlns:th="http://www.thymeleaf.org">
<meta charset="UTF-8" />
<head>
    <title>Home</title>
    <script th:src="@{sockjs.min.js}"></script>
    <script th:src="@{stomp.min.js}"></script>
    <script th:src="@{jquery.js}"></script>
</head>
<body>
<p>
    聊天室
</p>

<form id="wiselyForm">
    <textarea rows="4" cols="60" name="text"></textarea>
    <input type="submit"/>
</form>

<script th:inline="javascript">
    $('#wiselyForm').submit(function(e){
        e.preventDefault();
        var text = $('#wiselyForm').find('textarea[name="text"]').val();
        sendSpittle(text);
    });

    var sock = new SockJS("/endpointChat"); //1
    var stomp = Stomp.over(sock);
    stomp.connect('guest', 'guest', function(frame) {
        stomp.subscribe("/user/queue/notifications", handleNotification);//2
    });

    function handleNotification(message) {
        $('#output').append("<b>Received: " + message.body + "</b><br/>")
    }

    function sendSpittle(text) {
        stomp.send("/chat", {}, text);//3
    }
    $('#stop').click(function() {sock.close()});
</script>

<div id="output"></div>
</body>
</html>

二.在spring boot中建立spring Security,代碼以下圖所示:jquery

(spring Security是一個可以爲基於Spring的企業應用系統提供聲明式的安全訪問控制解決方案的安全框架。通俗地講就是爲你的系統提供安全權限,不是什麼人都能訪問你的系統,只有有權限的人才行!)web

1.先在pom.xml中引入spring Security的依賴,代碼以下圖所示:spring

            <!--spring-boot-security安全框架-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

 

2.WebSecurityConfig類瀏覽器

package com.wisely.ch7_6;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/","/login").permitAll()//1根路徑和/login路徑不攔截
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login") //2登錄頁面
                .defaultSuccessUrl("/chat") //3登錄成功轉向該頁面
                .permitAll()
                .and()
                .logout()
                .permitAll();
    }
    //4
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth
                .inMemoryAuthentication()
                .withUser("dzz").password("dzz").roles("USER")//這裏兩個是分別帳號和密碼(帳號:dzz密碼:dzz)
                .and()
                .withUser("zbb").password("zbb").roles("USER");//這裏兩個是分別帳號和密碼(帳號:zbb密碼:zbb)
    }
    //5忽略靜態資源的攔截
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/static/**");
    }
}

3.在原來的WsController類中增長聊天的方法handleChat(),代碼以下圖所示:安全

    @Autowired
    private SimpMessagingTemplate messagingTemplate;//1

    @MessageMapping("/chat")
    public void handleChat(Principal principal, String msg) { //2
        if (principal.getName().equals("dzz")) {//3
            messagingTemplate.convertAndSendToUser("zbb",
                    "/queue/notifications", principal.getName() + "-send:"
                            + msg);
        } else {
            messagingTemplate.convertAndSendToUser(dzz",
                    "/queue/notifications", principal.getName() + "-send:"
                            + msg);
        }
    }
}

(1)SimpMessagingTemplate用於向瀏覽器發送信息。websocket

(2)在spring mvc中,principal包含了登陸用戶的信息,在這裏咱們直接用。

(3)這裏是一段寫死的代碼,若是登陸的用戶是dzz,那就將消息發送給zbb,你們根據本身的需求進行修改。經過convertAndSendToUser()方法進行發送,第一個參數是信息接收的目標,第二個參數是要發送的地址,第三個參數是要發送的信息。

4.在原來的WebSocketConfig類中再建立一個節點(endpoint)和代理(MessageBroker),代碼以下圖所示:

package com.wisely.ch7_6;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer{

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


    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/queue","/topic"); //2
    }

}

5.在原來的WebMvcConfig類中加入/login和/chat的映射,以下圖:

           registry.addViewController("/login").setViewName("/login");
           registry.addViewController("/chat").setViewName("/chat");

三.效果演示

用兩個帳號登陸後,如圖所示:

 

 

dzz發送消息後zbb就能收到消息了,如圖所示:

 

websocket的一對一聊天演示到此就結束了,若有錯誤,歡迎指正。

相關文章
相關標籤/搜索