springboot实现websocket服务端、websocket客户端

  1. 依赖
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <exclusions>
                <exclusion>
                    <!--排除tomcat,使用jetty作为容器,jetty的连接数更高-->
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jetty</artifactId>
        </dependency>
  1. 代码实现
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import javax.websocket.ContainerProvider;
import javax.websocket.WebSocketContainer;

/**
 * websocket配置
 */
@Configuration
public class WebSocketConfig {
	//服务端配置
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
	//客户端配置
    @Bean
    public WebSocketContainer webSocketContainer() {
        WebSocketContainer webSocketContainer = ContainerProvider.getWebSocketContainer();
        webSocketContainer.setDefaultMaxSessionIdleTimeout(300000L);
        return webSocketContainer;
    }
}
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

/**
 * websocket的服务端
 */
@Component
@Slf4j
@ServerEndpoint("/WSServer/{pointSN}")
public class WSServer {

    public static ConcurrentHashMap<String, WSServer> webSocketMap = new ConcurrentHashMap<>();

    /**
     * 与客户端连接的session
     */
    private Session session;

    /**
     * 客户端id
     */
    private String id = "";

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("pointSN") String id) {
        this.id = id;
        this.session = session;

        if (webSocketMap.containsKey(id)) {
            webSocketMap.remove(id);

            webSocketMap.put(id, this);
        } else {

            webSocketMap.put(id, this);
        }

        log.info("客户端:" + id + ",连接成功");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if (webSocketMap.containsKey(id)) {
            webSocketMap.remove(id);

        }
        log.info("客户端:" + id + ",断开连接");
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("客户端:" + id + ",报文:" + message);

        sendMessage("收到");
    }


    /**
     * @param session
     * @param e
     */
    @OnError
    public void onError(Session session, Throwable e) {

        log.error("连接错误:" + this.id, e);
    }


    public void sendMessage(String message) {
//        try {
        this.session.getAsyncRemote().sendText(message);
//        } catch (IOException e) {
//            log.error("发送客户端:" + id + ",异常", e);
//        }
    }

    /**
     * 发送自定义消息
     */
    public static void sendInfo(String message, String id) {
        log.info("发送给客户端:" + id + ",报文:" + message);
        if (StringUtils.isNotBlank(id) && webSocketMap.containsKey(id)) {
            webSocketMap.get(id).sendMessage(message);
        } else {
            log.error("客户端:" + id + ",不在线");
        }
    }

}
import lombok.extern.slf4j.Slf4j;

import javax.websocket.*;
import java.net.URI;

/**
 * @Description:
 * @Author: feicongcong
 * @Date: 2022/7/19
 * @Version: V1.0
 */
@ClientEndpoint
@Slf4j
public class MyWSClient {

    private Session session;
    private String id;

    @OnOpen
    public void open(Session session) {
        log.info("客户端:" + id + ",连接服务端...");
        this.session = session;
    }

    @OnMessage
    public void onMessage(String message) {
        log.info("服务端:" + id + ",报文:"+ message);
    }

    @OnClose
    public void onClose() {
        log.info("客户端:" + id + ",服务端服务端断开连接");
    }

    /**
     * @param session
     * @param e
     */
    @OnError
    public void onError(Session session, Throwable e) {
        log.error("连接服务端错误:" + this.id, e);
    }

    /**
     * 发送客户端消息到服务端
     *
     * @param message 消息内容
     */
    public void send(String message) {

        this.session.getAsyncRemote().sendText(message);

    }

    public MyWSClient(String id) {
        this.id = id;
    }

    public MyWSClient() {
    }

    public static void main(String[] args) throws Exception {
        WebSocketContainer webSocketContainer = ContainerProvider.getWebSocketContainer();
        webSocketContainer.setDefaultMaxSessionIdleTimeout(300000L);


        WSClient wsClient = new WSClient();
        webSocketContainer.connectToServer(wsClient, new URI("ws://127.0.0.1:8082/demo/websocket/"+"id"));
        wsClient.send("message");
    }
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 使用 Spring Boot 实现 WebSocket 服务端和网页客户端需要以下步骤: 1. 在项目的 pom.xml 文件中添加 spring-boot-starter-websocket 依赖。 2. 创建一个 WebSocketConfig 类,并使用 @EnableWebSocketMessageBroker 注解开启 WebSocket 消息代理。 3. 在 WebSocketConfig 类中配置消息代理,可以使用 @Autowired 注入 SimpMessagingTemplate 类。 4. 创建一个 WebSocketController 类,并使用 @Controller 注解标记为控制器。在该类中可以定义处理客户端请求的方法,使用 @MessageMapping 注解标记方法,并使用 SimpMessagingTemplate 向客户端发送消息。 5. 在网页客户端中,使用 JavaScript 和 WebSocket API 连接服务器并发送和接收消息。 6. 在 spring boot 启动类中添加 @EnableWebSocket 即可。 更多细节请参考Spring官网相关文档。 ### 回答2: 在使用Spring Boot实现WebSocket服务端和网页客户端时,需要进行以下步骤: 1. 首先,创建一个Spring Boot项目,并在pom.xml文件中添加相关的依赖项,包括Spring Web和Spring WebSocket依赖。 2. 创建一个WebSocket配置类,通过@EnableWebSocket注解启用WebSocket,并实现WebSocketConfigurer接口,重写registerWebSocketHandlers方法。 3. 在registerWebSocketHandlers方法中,创建一个WebSocketHandler对象,并使用registerHandler方法注册该Handler,并指定相关的WebSocket连接路径。 4. 在WebSocketHandler中,继承TextWebSocketHandler,重写handleTextMessage方法来处理接收到的文本消息。 5. 在handleTextMessage方法中,可以处理接收到的消息,并通过WebSocketSession对象的sendMessage方法发送消息给客户端。 6. 创建一个Web页面作为WebSocket客户端,并使用JavaScript中的WebSocket对象进行连接,指定WebSocket连接路径。 7. 在客户端使用WebSocket对象的onopen、onmessage、onclose和onerror方法来处理连接建立、接收到消息、连接关闭和连接错误的情况。 使用以上步骤,可以实现一个简单的WebSocket服务端和网页客户端。当客户端连接到服务端时,服务端可以接收到客户端发送的消息,并进行相应的处理,然后将处理结果发送给客户端。而客户端可以通过WebSocket对象发送消息给服务端,并接收到服务端发送的消息,完成双向通信的功能。 ### 回答3: 使用Spring Boot实现WebSocket服务端和网页客户端可以通过以下几个步骤完成。 1. 首先,在pom.xml文件中添加Spring BootWebSocket依赖。 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` 2. 接下来,在Spring Boot的主类上添加@EnableWebSocket注解,启用WebSocket支持。 ```java @SpringBootApplication @EnableWebSocket public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 3. 创建一个WebSocket处理类,实现WebSocketHandler接口,并重写相应的方法。 ```java @Component public class MyWebSocketHandler implements WebSocketHandler { @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { // 当与客户端建立连接后触发 } @Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { // 当接收到客户端消息时触发 } @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { // 当发生传输错误时触发 } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { // 当与客户端断开连接后触发 } @Override public boolean supportsPartialMessages() { return false; } } ``` 4. 在WebSocket处理类中可以利用session对象与客户端进行交互,发送消息或者接收客户端发送的消息。例如,可以在`afterConnectionEstablished`方法中使用`session.sendMessage()`方法发送欢迎消息给客户端,在`handleMessage`方法中处理客户端发送的消息。 5. 创建一个配置类来注册WebSocketHandler,并指定WebSocket的访问路径。 ```java @Configuration public class WebSocketConfig implements WebSocketConfigurer { @Autowired private MyWebSocketHandler myWebSocketHandler; @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(myWebSocketHandler, "/websocket").setAllowedOrigins("*"); } } ``` 6. 在网页客户端中,可以利用JavaScript的WebSocket API来与服务端建立连接,并进行通信。 ```javascript var socket = new WebSocket('ws://localhost:8080/websocket'); socket.onopen = function() { // 当与服务端建立连接后触发 } socket.onmessage = function(event) { var message = event.data; // 接收服务端发送的消息 } socket.onclose = function(event) { // 当与服务端断开连接后触发 } function sendMessage(message) { socket.send(message); // 发送消息给服务端 } ``` 以上就是使用Spring Boot实现WebSocket服务端和网页客户端的基本步骤。可以根据实际需求,进一步细化和定制化相关功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值