java springboot 中使用webSocket接入openAI接口调用chatGPT3.5接口实现自由返回
在springboot中添加webSocketServer
@Component
@Anonymous
@ServerEndpoint(“/websocket/{id}”) // 访问路径: ws://localhost:8080/websocket
public class WebSocketServer {
protected static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);
/**
* 客户端ID
*/
private String id="";
/**
* 与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
private Session session;
/**
* 记录当前在线连接数(为保证线程安全,须对使用此变量的方法加lock或synchronized)
*/
private static int onlineCount = 0;
/**
* 用来存储当前在线的客户端(此map线程安全)
*/
private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
private static ConcurrentHashMap<String, StringBuffer> stringBufferMap = new ConcurrentHashMap<>();
/**
* 连接建立成功后调用
*/
@OnOpen
public void onOpen(@PathParam(value = "id") String id, Session session) {
this.session = session;
// 接收到发送消息的客户端编号
this.id = id;
// 加入map中
StringBuffer stringBuffer = new StringBuffer();
stringBufferMap.put(id,stringBuffer);
webSocketMap.put(id, this);
// try {
// sendMessage(“WebSocket连接成功”);
// } catch (Exception e) {
//
// }
}
/**
* 发送消息
* @param message 要发送的消息
*/
private void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
// 关闭连接调用
@OnClose
public void close() {
}
// 接收消息
@OnMessage
public void message(String message, Session session) {
System.out.println("client send: " + messag