springboot+websocket實現簡單的在線聊天功能


效果如下:

 

 

java實現邏輯:

1.引入maven依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2.創建一個服務端
package com.example.demo.controller;

import org.springframework.web.bind.annotation.RestController;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/websocket/{name}")
@RestController
public class WebSocketServer {

    //存儲客戶端的連接對象,每個客戶端連接都會產生一個連接對象
    private static ConcurrentHashMap<String,WebSocketServer> map=new ConcurrentHashMap();
    //每個連接都會有自己的會話
    private Session session;
    private String name;
    @OnOpen
    public void open(@PathParam("name") String name, Session session){
        map.put(name,this);
        System.out.println(name+"連接服務器成功");
        System.out.println("客戶端連接個數:"+getConnetNum());

        this.session=session;
        this.name=name;
    }
    @OnClose
    public void close(){
        map.remove(name);
        System.out.println(name+"斷開了服務器連接");
    }
    @OnError
    public void error(Throwable error){
        error.printStackTrace();
        System.out.println(name+"出現了異常");
    }
    @OnMessage
    public void getMessage(String message) throws IOException {
        System.out.println("收到"+name+":"+message);
        System.out.println("客戶端連接個數:"+getConnetNum());

        Set<Map.Entry<String, WebSocketServer>> entries = map.entrySet();
        for (Map.Entry<String, WebSocketServer> entry : entries) {
            if(!entry.getKey().equals(name)){//將消息轉發到其他非自身客戶端
                entry.getValue().send(message);

            }
        }
    }

    public void send(String message) throws IOException {
        if(session.isOpen()){
           session.getBasicRemote().sendText(message);
        }
    }

    public int  getConnetNum(){
        return map.size();
    }
}
3.一個配置類
@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
    
}

//客戶端html代碼,此處創建2個客戶端,一個叫xiaoMing一個叫xiaoHua

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>當前用戶xiaoMing</title>
</head>
<style>
    #message{
        width: 50%;
        height: 500px;
        border: 1px solid black;
        background-color: darkgray;

    }

    #inputVal{
        width: 50%;
    }
    input{
        width: 92%;
    }
</style>
<body>
<h1>當前用戶xiaoMing</h1>
<div id="message">

</div>
<div id="inputVal">
    <input type="text" name="text">
    <button onclick="send()">發送</button>
</div>

<script>
    var messageEl=document.getElementById("message");
    var inputEl=document.getElementsByTagName("input")[0];
    var websocket=null;
    if('WebSocket' in window){
        websocket=new WebSocket("ws:localhost:2300/websocket/xiaoMing");
    }else {
        alert("瀏覽器不支持");

    }
    websocket.onopen=function () {
        console.log("webscoket已經連接成功");
        addMessage("webscoket已經連接成功");

    };
    websocket.onclose=function () {
        console.log("webscoket連接失敗");
        addMessage("webscoket連接失敗");
    };
    websocket.onmessage=function (event) {
        addMessage(event.data);
    };
    websocket.onerror=function () {
        console.log("webscoket連接失敗");
        addMessage("webscoket連接失敗");
    };
    function addMessage(message) {
        messageEl.innerHTML+=message+"</br>";
    }
    
    function send() {
        websocket.send("xiaoMing:"+inputEl.value);
        messageEl.innerHTML+="我:"+inputEl.value+"</br>";
    }


</script>

</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>當前用戶xiaoHua</title>
</head>
<style>
    #message{
        width: 50%;
        height: 500px;
        border: 1px solid black;
        background-color: darkgray;
    }

    #inputVal{
        width: 50%;
    }
    input{
        width: 92%;
    }
</style>
<body>
<h1>當前用戶xiaoHua</h1>
<div id="message">

</div>
<div id="inputVal">
    <input type="text" name="text">
    <button onclick="send()">發送</button>
</div>

<script>
    var messageEl=document.getElementById("message");
    var inputEl=document.getElementsByTagName("input")[0];

    var websocket=null;
    if('WebSocket' in window){
        websocket=new WebSocket("ws:localhost:2300/websocket/xiaoHua");
    }else {
        alert("瀏覽器不支持");

    }
    websocket.onopen=function () {
        console.log("webscoket已經連接成功");
        addMessage("webscoket已經連接成功");

    };
    websocket.onclose=function () {
        console.log("webscoket連接失敗");
        addMessage("webscoket連接失敗");
    };
    websocket.onmessage=function (event) {
        addMessage(event.data);
    };
    websocket.onerror=function () {
        console.log("webscoket連接失敗");
        addMessage("webscoket連接失敗");
    };
    function addMessage(message) {
        messageEl.innerHTML+=message+"</br>";
    }

    function send() {
        websocket.send("xiaoHua:"+inputEl.value);
        messageEl.innerHTML+="我:"+inputEl.value+"</br>";
    }


</script>

</body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM