springboot builds webSocket dialogue

Now that AI tools are so popular, I have created an AI dialog box myself, which requires the use of webSocket
How to access the ai component can be referred toJava docking with Alibaba Yuntong Yiqianwen API multi-round dialogue undertaking context
1. Maven adds jar package

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

2. Create WebSocketConfig

package com.ruoyi.web.controller.app;

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
    public ServerEndpointExporter serverEndpointExporter(){
    
    
        return new ServerEndpointExporter();
    }
}

3. Create WebSocketServer

package com.ruoyi.web.controller.app;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

@Component
@ServerEndpoint("/webSocket/{username}")
public class WebSocketServer {
    
    
    /**
     * 该map用来存放每个用户对应的Session对象。
     */
    private static Map<String, Session> clients = new ConcurrentHashMap<>();

    
    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam("username") String username, Session session) throws IOException {
    
    
        if (username == null) {
    
    
            return;
        }
        clients.put(username, session);
        System.out.println("用户:" + username + "连接到websocke");
    }
    
    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam("username") String username) throws IOException {
    
    
        clients.remove(username);
        System.out.println("用户:" + username + "断开websocket");
    }

    @OnMessage
    public void onMessage(String json) throws IOException {
    
    
        System.out.println("前端发送的信息为:" + json);
        JSONObject jsonObject = JSONObject.parseObject(json);
        String user = jsonObject.getString("user");
        String msg = jsonObject.getString("msg");
        Session session = clients.get(user);
        //如果这个好友在线就直接发给他
        if (session != null) {
    
    
            sendMessageTo(msg,session);
        } else {
    
    
            System.out.println("对方不在线,对方名字为:" + user);
        }
    }
    
    /**
     * 出现异常触发的方法
     */
    @OnError
    public void onError(Session session, Throwable error) {
    
    
        error.printStackTrace();
    }

    /**
     * 单发给某人
     */
    public void sendMessageTo(String message, Session session) throws IOException {
    
    
        session.getBasicRemote().sendText(message);
    }
}

4. Start testing
After writing the code, start springboot and start testing
Use the ApiPost tool to test
ws ://localhost:80/webSocket/Zhang San
User Zhang San links to the webSocket service
Zhang San sends json data to Li Si {"msg":" The king of heaven overshadows the tigers of the earth.","user":"李思"}
Insert image description here
ws://localhost:80/webSocket/李思
Li Si also links webSocket service
Here you can see the received data
and reply {"msg":"Chicken stewed with mushrooms.","user":"Zhang San" }To Zhang San
Insert image description here
Zhang San also met the secret code and the conversation was completed.
Insert image description here

Guess you like

Origin blog.csdn.net/woshiabc111/article/details/134659725