一个最简单基于spring的websocket服务端+客户端实现案例

1、服务端

代码分为两部分:

一个是服务器终端类:用java注解来监听连接@ServerEndpoint、连接成功@OnOpen、连接失败@OnClose、收到消息等状态@OnMessage

java 复制代码
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

@Component
@ServerEndpoint("/websocket/fqa")
public class QwenWebSocket {

    @OnOpen
    public void onOpen(Session session){
        System.out.println("WebSocket opened: " + session.getId());
    }

    @OnMessage
    public void onMessage(String message, Session session){
        System.out.println("Message received: " + message);
        try{
            session.getBasicRemote().sendText("Echo: " + message);
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose(Session session){
        System.out.println("WebSocket closed: " + session.getId());
    }

    @OnError
    public void onError(Throwable t){
        t.printStackTrace();
    }
}

一个是websocket的配置类,用于把spring中的ServerEndpointExporter对象注入进来

java 复制代码
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {
    /**
     * 这个bean的注册,用于扫描带有@ServerEndpoint的注解成为websocket,如果你使用外置的tomcat就不需要该配置文件
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

2、客户端

普通的java工程即可,不需要是spring。

java 复制代码
import javax.websocket.*;
import java.net.URI;


@ClientEndpoint
public class MyWebSocketClient {

    @OnOpen
    public void onOpen(Session session){
        System.out.println("Connected to server");
    }

    @OnMessage
    public void onMessage(String message){
        System.out.println("Received message: " + message);
    }

    @OnClose
    public void onClose(CloseReason reason){
        System.out.println("Closing: " + reason.getReasonPhrase());
    }

    public static void main(String[] args) {
        try{
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            URI uri = URI.create("ws://localhost:8080/websocket/fqa");
            Session session = container.connectToServer(MyWebSocketClient.class, uri);
            session.getBasicRemote().sendText("I'm client!");
            Thread.sleep(10000);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

3、效果

客户端显示:

Connected to server

Received message: Echo: I'm client!

服务端显示:

WebSocket opened: 4

Message received: I'm client!

WebSocket closed: 4

相关推荐
xzl043 小时前
小智服务端chat入口工具调用流程
java·服务器·前端
CTO Plus技术服务中3 小时前
2026版Java web高并发面试题和参考答案
java·jvm·spring·spring cloud·面试·tomcat·java-consul
2301_803554523 小时前
Qt中connect()实现信号与槽连接这一核心机制
java·数据库·qt
峥嵘life3 小时前
Android16 EDLA【CTS】CtsNetTestCases存在fail项
android·java·linux·学习·elasticsearch
七夜zippoe3 小时前
Python网络编程实战:从TCP/IP到WebSocket的协议演进与核心技术解析
网络·python·websocket·tcp/ip·socket·心跳机制
九皇叔叔4 小时前
【01】SpringBoot3 MybatisPlus 工程创建
java·mybatis·springboot3·mybatis plus
tqs_123454 小时前
Spring Boot 和 Spring异同
java
橘颂TA4 小时前
C++ 信号量
java·开发语言
程序猿20234 小时前
Java Thread
java·开发语言·python
梅梅绵绵冰4 小时前
springboot初步1
java·前端·spring boot