WebSocket+SpringBoot+Vue를 사용하여 간단한 웹 채팅방을 구축하는 방법
1. 데이터베이스 구성
두 명의 사용자 admin과 wskh를 추가하는 매우 간단한 테이블 구성
2. 백엔드 구성
2.1 주요 종속성 소개
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
2.2 WebSocket 구성 클래스
WebSocketConfig의 역할은 다음과 같습니다. WebSocket 모니터링
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; /** * @Author:WSKH * @ClassName:WebSocketConfig * @ClassType:配置类 * @Description:WebSocket配置类 * @Date:2022/1/25/12:21 * @Email:1187560563@qq.com * @Blog:https://blog.csdn.net/weixin_51545953?type=blog */ @Configuration public class WebSocketConfig { /** * 开启webSocket * @return */ @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }
WebSocketServer는 메시지 전송 이벤트, 연결 설정 이벤트, 연결 종료 이벤트 등과 같은 일부 이벤트를 작성했습니다.
import com.wskh.chatroom.util.FastJsonUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.io.EOFException; import java.io.IOException; import java.util.concurrent.ConcurrentHashMap; @ServerEndpoint("/websocket/{sid}") @Component public class WebSocketServer { private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class); private static int onlineCount = 0; private static ConcurrentHashMap<String,WebSocketServer> webSocketServerMap = new ConcurrentHashMap<>(); private Session session; private String sid; @OnOpen public void onOpen(Session session, @PathParam("sid") String sid) { this.sid = sid; this.session = session; webSocketServerMap.put(sid, this); addOnlineCount(); log.info("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount()); try { sendInfo("openSuccess:"+webSocketServerMap.keySet()); } catch (IOException e) { e.printStackTrace(); } } @OnClose public void onClose() { webSocketServerMap.remove(sid); subOnlineCount(); log.info("有一连接关闭!当前在线人数为" + getOnlineCount()); try { sendInfo("openSuccess:"+webSocketServerMap.keySet()); } catch (IOException e) { e.printStackTrace(); } } @OnMessage public void onMessage(String message) throws IOException { if("ping".equals(message)) { sendInfo(sid, "pong"); } if(message.contains(":")) { String[] split = message.split(":"); sendInfo(split[0], "receivedMessage:"+sid+":"+split[1]); } } @OnError public void onError(Session session, Throwable error) { if(error instanceof EOFException) { return; } if(error instanceof IOException && error.getMessage().contains("已建立的连接")) { return; } log.error("发生错误", error); } /** * 实现服务器主动推送 */ public void sendMessage(String message) throws IOException { synchronized (session) { this.session.getBasicRemote().sendText(message); } } public static void sendObject(Object obj) throws IOException { sendInfo(FastJsonUtils.convertObjectToJSON(obj)); } public static void sendInfo(String sid,String message) throws IOException { WebSocketServer socketServer = webSocketServerMap.get(sid); if(socketServer != null) { socketServer.sendMessage(message); } } public static void sendInfo(String message) throws IOException { for(String sid : webSocketServerMap.keySet()) { webSocketServerMap.get(sid).sendMessage(message); } } public static void sendInfoByUserId(Long userId,Object message) throws IOException { for(String sid : webSocketServerMap.keySet()) { String[] sids = sid.split("id"); if(sids.length == 2) { String id = sids[1]; if(userId.equals(Long.parseLong(id))) { webSocketServerMap.get(sid).sendMessage(FastJsonUtils.convertObjectToJSON(message)); } } } } public static Session getWebSocketSession(String sid) { if(webSocketServerMap.containsKey(sid)) { return webSocketServerMap.get(sid).session; } return null; } public static synchronized void addOnlineCount() { onlineCount++; } public static synchronized void subOnlineCount() { onlineCount--; } public static synchronized int getOnlineCount() { return onlineCount; } }
2.3 크로스 도메인 구성
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override // 跨域配置 public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE") .maxAge(3600) .allowCredentials(true); } }
2.4 메시지 전송을 위한 제어 클래스
/** * @Author:WSKH * @ClassName:MsgController * @ClassType:控制类 * @Description:信息控制类 * @Date:2022/1/25/12:47 * @Email:1187560563@qq.com * @Blog:https://blog.csdn.net/weixin_51545953?type=blog */ @ApiModel("信息控制类") @RestController @RequestMapping("/chatroom/msg") public class MsgController { @ApiOperation("发送信息方法") @PostMapping("/sendMsg") public R sendMsg(String msg) throws IOException { WebSocketServer.sendInfo(msg); return R.ok().message("发送成功"); } }
여기 포인트, 백엔드 일부 부분은 일반적으로 구성됩니다.
3. 프런트엔드 구축
이 글에서는 vue-admin-template-master 템플릿을 사용하여 채팅방의 프런트엔드를 구축합니다.
3.1 사용자 정의 파일 websocket.js
다음 파일을 api 폴더에 넣습니다.
//websocket.js import Vue from 'vue' // 1、用于保存WebSocket 实例对象 export const WebSocketHandle = undefined // 2、外部根据具体登录地址实例化WebSocket 然后回传保存WebSocket export const WebsocketINI = function(websocketinstance) { this.WebSocketHandle = websocketinstance this.WebSocketHandle.onmessage = OnMessage } // 3、为实例化的WebSocket绑定消息接收事件:同时用于回调外部各个vue页面绑定的消息事件 // 主要使用WebSocket.WebSocketOnMsgEvent_CallBack才能访问 this.WebSocketOnMsgEvent_CallBack 无法访问很诡异 const OnMessage = function(msg) { // 1、消息打印 // console.log('收到消息:', msg) // 2、如果外部回调函数未绑定 结束操作 if (!WebSocket.WebSocketOnMsgEvent_CallBack) { console.log(WebSocket.WebSocketOnMsgEvent_CallBack) return } // 3、调用外部函数 WebSocket.WebSocketOnMsgEvent_CallBack(msg) } // 4、全局存放外部页面绑定onmessage消息回调函数:注意使用的是var export const WebSocketOnMsgEvent_CallBack = undefined // 5、外部通过此绑定方法 来传入的onmessage消息回调函数 export const WebSocketBandMsgReceivedEvent = function(receiveevent) { WebSocket.WebSocketOnMsgEvent_CallBack = receiveevent } // 6、封装一个直接发送消息的方法: export const Send = function(msg) { if (!this.WebSocketHandle || this.WebSocketHandle.readyState !== 1) { // 未创建连接 或者连接断开 无法发送消息 return } this.WebSocketHandle.send(msg)// 发送消息 } // 7、导出配置 const WebSocket = { WebSocketHandle, WebsocketINI, WebSocketBandMsgReceivedEvent, Send, WebSocketOnMsgEvent_CallBack } // 8、全局绑定WebSocket Vue.prototype.$WebSocket = WebSocket

import '@/utils/websocket' // 全局引入 WebSocket 通讯组件
위 내용은 WebSocket+SpringBoot+Vue를 사용하여 간단한 웹 채팅방을 구축하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











vue.js에서 JS 파일을 참조하는 세 가지 방법이 있습니다. & lt; script & gt; 꼬리표;; mounted () 라이프 사이클 후크를 사용한 동적 가져 오기; Vuex State Management Library를 통해 수입.

vue.js에서 bootstrap 사용은 5 단계로 나뉩니다 : Bootstrap 설치. main.js.의 부트 스트랩 가져 오기 부트 스트랩 구성 요소를 템플릿에서 직접 사용하십시오. 선택 사항 : 사용자 정의 스타일. 선택 사항 : 플러그인을 사용하십시오.

vue.js의 시계 옵션을 사용하면 개발자가 특정 데이터의 변경 사항을들을 수 있습니다. 데이터가 변경되면 콜백 기능을 트리거하여 업데이트보기 또는 기타 작업을 수행합니다. 구성 옵션에는 즉시 콜백을 실행할지 여부와 DEEP를 지정하는 즉시 포함되며, 이는 객체 또는 어레이에 대한 변경 사항을 재귀 적으로 듣는 지 여부를 지정합니다.

vue.js에서 게으른 로딩을 사용하면 필요에 따라 부품 또는 리소스를 동적으로로드 할 수 있으므로 초기 페이지로드 시간을 줄이고 성능을 향상시킵니다. 특정 구현 방법에는 & lt; keep-alive & gt를 사용하는 것이 포함됩니다. & lt; 구성 요소는 & gt; 구성 요소. 게으른 하중은 FOUC (Splash Screen) 문제를 일으킬 수 있으며 불필요한 성능 오버 헤드를 피하기 위해 게으른 하중이 필요한 구성 요소에만 사용해야합니다.

CSS 애니메이션 또는 타사 라이브러리를 사용하여 VUE에서 Marquee/Text Scrolling Effects를 구현하십시오. 이 기사는 CSS 애니메이션 사용 방법을 소개합니다. & lt; div & gt; CSS 애니메이션을 정의하고 오버플로를 설정하십시오 : 숨겨진, 너비 및 애니메이션. 키 프레임을 정의하고 변환을 설정하십시오 : Translatex () 애니메이션의 시작과 끝에서. 지속 시간, 스크롤 속도 및 방향과 같은 애니메이션 속성을 조정하십시오.

Vue DevTools를 사용하여 브라우저 콘솔에서 vue 탭을 보면 VUE 버전을 쿼리 할 수 있습니다. npm을 사용하여 "npm list -g vue"명령을 실행하십시오. package.json 파일의 "종속성"객체에서 vue 항목을 찾으십시오. Vue Cli 프로젝트의 경우 "vue -version"명령을 실행하십시오. & lt; script & gt에서 버전 정보를 확인하십시오. vue 파일을 나타내는 html 파일의 태그.

vue.js는 이전 페이지로 돌아갈 수있는 네 가지 방법이 있습니다. $ router.go (-1) $ router.back () 사용 & lt; router-link to = & quot;/quot; Component Window.history.back () 및 메소드 선택은 장면에 따라 다릅니다.

HTML 템플릿의 버튼을 메소드에 바인딩하여 VUE 버튼에 함수를 추가 할 수 있습니다. 메소드를 정의하고 VUE 인스턴스에서 기능 로직을 작성하십시오.
