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");
    }
}

你可能感兴趣的:(springboot,Java网络编程,websocket,spring,boot,java)