Springboot WebSocket极简聊天室

本文介绍了如何在SpringBoot应用中使用WebSocket进行实时通信,包括添加依赖、配置WebSocket处理器和前端HTML页面的交互示例。适合初学者研究和扩展WebSocket功能。
摘要由CSDN通过智能技术生成

首先是要在pom.xml添加WebSocket的依赖,然后就可以编写下面代码
 
创建启动类 ChatRoomDemoApplication :

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.springframework.web.socket.WebSocketSession;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@SpringBootApplication
@EnableWebSocket
public class ChatRoomDemoApplication implements WebSocketConfigurer {

    private final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

    public static void main(String[] args) {
        SpringApplication.run(ChatRoomDemoApplication.class, args);
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(chatWebSocketHandler(), "/chat").setAllowedOrigins("*");
    }

    @Bean
    public WebSocketHandler chatWebSocketHandler() {
        return new TextWebSocketHandler() {
            @Override
            public void afterConnectionEstablished(WebSocketSession session) throws Exception {
                sessions.put(session.getId(), session);
            }

            @Override
            public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
                sessions.remove(session.getId());
            }

            @Override
            protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
                for (WebSocketSession webSocketSession : sessions.values()) {
                    webSocketSession.sendMessage(message);
                }
            }
        };
    }
}

前端代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat Room Demo</title>
</head>
<body>
    <div id="chat-box"></div>
    <input type="text" id="message" placeholder="Type your message here...">
    <button onclick="sendMessage()">Send</button>

    <script>
        const socket = new WebSocket("ws://localhost:8080/chat");
        
        socket.onmessage = function(event) {
            const message = event.data;
            document.getElementById("chat-box").innerHTML += "<p>" + message + "</p>";
        };
        
        function sendMessage() {
            const message = document.getElementById("message").value;
            socket.send(message);
            document.getElementById("message").value = "";
        }
    </script>
</body>
</html>

然后就可以启动试试了,这个项目适合对于WebSocket一头雾水的同志研究学习,后面可以自行拆分拓展代码

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值