JavaScript-websocket的基本使用
- 文章说明
- JavaScript端
- 后台--服务端
- 连接演示
文章说明
本文主要介绍JavaScript中websocket的基本使用,后台采用Java编写WebSocket服务端
JavaScript端
websocket工具类
class Socket {constructor(url, onopen, onmessage, onerror, onclose) {this.websocket = null;this.socketInit(url, onopen, onmessage, onerror, onclose);}socketInit(url, onopen, onmessage, onerror, onclose) {this.websocket = new WebSocket(url);this.websocket.onopen = (e) => {onopen(e);};this.websocket.onmessage = (e) => {onmessage(e);};this.websocket.onclose = (e) => {onclose(e);};this.websocket.onerror = (e) => {onerror(e);};}send(message) {this.websocket.send(JSON.stringify(message));}close() {this.websocket.close();}
}export default Socket;
App.vue使用websocket,创建连接
<template><button @click="open">开启websocket</button>
</template><script setup>
import Socket from "@/websocket";function open() {new Socket("ws://127.0.0.1:8081", (e) => {console.log(e)}, (e) => {console.log(e)}, (e) => {console.log(e)}, (e) => {console.log(e)});
}
</script>
后台–服务端
引入依赖
<dependency><groupId>org.java-websocket</groupId><artifactId>Java-WebSocket</artifactId><version>1.5.3</version>
</dependency>
服务端代码(这里只是简单的演示服务器创建WebSocket,并等待连接,然后发送消息,之后关闭;非常简陋,实际情况中应采用线程,并设置关闭事件,不自动关闭)
package com.boot.util;import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;import java.net.InetSocketAddress;/*** @author bbyh* @date 2024/7/3 15:17*/
public class TestWebSocketServer {public static void main(String[] args) throws Exception {WebSocketServer webSocketServer = new WebSocketServer(new InetSocketAddress(8081)) {@Overridepublic void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {System.out.println("onOpen");}@Overridepublic void onClose(WebSocket webSocket, int i, String s, boolean b) {System.out.println("onClose");}@Overridepublic void onMessage(WebSocket webSocket, String s) {System.out.println("onMessage");}@Overridepublic void onError(WebSocket webSocket, Exception e) {System.out.println("onError");}@Overridepublic void onStart() {System.out.println("onStart");}};webSocketServer.start();Thread.sleep(20000);webSocketServer.broadcast("你好,我是服务端WebSocket");webSocketServer.stop();}
}
连接演示
先运行Java的服务器端,创建监听,程序设置在20秒后发送消息并关闭,所以需要迅速调用JavaScript端的连接