Springboot 实现Websocket 客户端 +服务端

Websocket 客户端 +服务端 (用户——TCP连接)

服务端

pom.xml

  		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
        </dependency>

代码实现

package com.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * @author hy
 * @description:
 * @date 2021/01/18
 */

@Component
public class WebSocketConfig {
    /**
     * ServerEndpointExporter 作用
     *
     * 这个Bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint
     *
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}


package com.example.controller;

/**
 * @author hy
 * @description:
 * @date 2021/01/18
 */

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 * @ServerEndpoint 这个注解有什么作用?
 *
 * 这个注解用于标识作用在类上,它的主要功能是把当前类标识成一个WebSocket的服务端
 * 注解的值用户客户端连接访问的URL地址
 *
 */

@Slf4j
@Component
@ServerEndpoint("/websocket")
public class WebSocket {

    /**
     *  与某个客户端的连接对话,需要通过它来给客户端发送消息
     */
    private Session session;

    /**
     * 标识当前连接客户端的用户名
     */
    private String name;

    /**
     *  用于存所有的连接服务的客户端,这个对象存储是安全的
     */
    private static ConcurrentHashMap<String,WebSocket> webSocketSet = new ConcurrentHashMap<>();


    @OnOpen
    public void OnOpen(){

        log.info("[WebSocket] 连接成功");
    }


    @OnClose
    public void OnClose(){
        webSocketSet.remove(this.name);
        log.info("[WebSocket] 退出成功");
    }

    @OnMessage
    public void OnMessage(String message,Session session){
        log.info("[WebSocket] 收到消息:{}",message);
        log.info("[WebSocket] 收到消息:{}",session);
        //判断是否需要指定发送,具体规则自定义
        if(message.indexOf("TOUSER") == 0){
            String name = message.substring(message.indexOf("TOUSER")+6,message.indexOf(";"));
            this.session = session;
            this.name = name;
            // name是用来表示唯一客户端,如果需要指定发送,需要指定发送通过name来区分
            log.info(name);
            webSocketSet.put(name,this);
            AppointSending(name,message.substring(message.indexOf(";")+1,message.length()));
        }else{
            GroupSending(message);
        }

    }

    /**
     * 群发
     * @param message
     */
    public void GroupSending(String message){
        for (String name : webSocketSet.keySet()){
            try {
                webSocketSet.get(name).session.getBasicRemote().sendText(message);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 指定发送
     * @param name
     * @param message
     */
    public void AppointSending(String name,String message){
        try {
            webSocketSet.get(name).session.getBasicRemote().sendText(message);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

客户端

pom.xml

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--websocket作为客户端-->
        <dependency>
            <groupId>org.java-websocket</groupId>
            <artifactId>Java-WebSocket</artifactId>
            <version>1.3.5</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
        </dependency>

代码实现

package com.example.controller;


import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URI;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author hy
 * @description:
 * @date 2021/01/18
 */
@RestController
@RequestMapping("/websocket1")
@Slf4j
public class MessageController {

    private static ConcurrentHashMap<String, WebSocketClient> webSocketSet = new ConcurrentHashMap<>();

    @GetMapping("/connect")
    public void sendMessage(String name) {
        WebSocketClient webSocketClient = webSocketClient(name);
        webSocketSet.put(name,webSocketClient);
    }

    @GetMapping("/chat")
    public void chat(String name, String message) {
        webSocketSet.get(name).send(message);
    }

    public WebSocketClient webSocketClient(String name) {
        try {
            WebSocketClient webSocketClient = new WebSocketClient(new URI("ws://localhost:8085/websocket/"+name), new Draft_6455()) {
                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    log.info("[websocket] 连接成功");
                }

                @Override
                public void onMessage(String message) {
                    log.info("[websocket] 收到消息={}", message);
                }

                @Override
                public void onClose(int code, String reason, boolean remote) {
                    log.info("[websocket] 退出连接");
                }

                @Override
                public void onError(Exception ex) {
                    log.info("[websocket] 连接错误={}", ex.getMessage());
                }
            };
            webSocketClient.connect();
            return webSocketClient;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值