久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術(shù)文章
文章詳情頁

Springboot基于websocket實(shí)現(xiàn)簡單在線聊天功能

瀏覽:5日期:2023-05-09 09:29:37

添加maven依賴

<?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'> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.5.RELEASE</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>springboot-websocket</artifactId> <name>springboot-websocket</name> <dependencies> <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> </dependencies></project>

添加websocket配置

@Configuration@EnableWebSocketpublic class MyWebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(myHandler(), '/myHandler').setAllowedOrigins('*'); } @Bean public WebSocketHandler myHandler() { return new MyTextWebSocketHandler(); }}

實(shí)現(xiàn)具體的handler

public class MyTextWebSocketHandler extends TextWebSocketHandler { private Set<WebSocketSession> sessions = new HashSet<>(); @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { if (session.isOpen()) { sessions.add(session); } sendToAll(message); } private void sendToAll(TextMessage message) throws IOException { for (WebSocketSession session : sessions) { session.sendMessage(message); } } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { sessions.remove(session); }}

即可通過ws://localhost:8080/myHandler訪問websocket

添加測試頁面:

<html><script type='text/javascript'> if ('WebSocket' in window) { var ws = new WebSocket('ws://localhost:8080/myHandler'); ws.onopen = function () { }; ws.onmessage = function (evt) { document.getElementById(’messageDiv’).innerHTML += evt.data + '</br>'; }; ws.onclose = function () { console.log('close connect'); }; } else { alert('您的瀏覽器不支持 WebSocket!'); } function send() { ws.send(document.getElementById('input').value + ': ' + document.getElementById('message').value); }</script></head><body>當(dāng)前用戶: <input /><br/><a href='http://www.baoyu77737.com/bcjs/13700.html#' rel='external nofollow' onclick='send();'>發(fā)送消息</a>: <input /><div id='messageDiv'></div></body></html>

即可實(shí)現(xiàn)簡單的通信功能

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: Spring
相關(guān)文章:
主站蜘蛛池模板: 嘉义县| 凤山市| 海盐县| 佛坪县| 伊金霍洛旗| 建湖县| 嘉定区| 绵阳市| 嘉善县| 静宁县| 韶关市| 永年县| 华容县| 湘阴县| 晋中市| 荔浦县| 集贤县| 崇州市| 新疆| 吴川市| 奎屯市| 抚松县| 会昌县| 永州市| 郁南县| 凯里市| 永福县| 灵山县| 泌阳县| 云霄县| 云和县| 于都县| 阳泉市| 屯留县| 新竹县| 宜宾县| 盐城市| 祁连县| 三明市| 高尔夫| 湟源县|