天天看點

SpringBoot--WebSocket

目錄結構:

SpringBoot--WebSocket

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 >

<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;

@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

SpringBoot--WebSocket

繼續閱讀