gpt4 book ai didi

javascript - WebSocket 关闭并出现协议(protocol)错误 1002

转载 作者:行者123 更新时间:2023-12-04 01:09:39 25 4
gpt4 key购买 nike

我正在实现 WebSocket 消息命令行客户端。
我已检查此错误是否与协议(protocol)问题相对应。我将ws升级到最新的7.4.1。在后端,我使用版本为 2.3.4.RELEASE 的 Spring Boot Websockets。
据说造成这种情况的两个主要原因是数据包丢失或格式错误的消息。
我做了一些检查来检查这些,但似乎没有一个是有效的。
我测试的消息很小,因此消息大小不应该是这种情况。连接完全在本地主机上。
我用 3 个用户测试解决方案,有时我会收到此错误,有时不会。
有人可以帮我弄清楚如何摆脱这种类型的错误吗?
这是我用于客户端发送消息的代码:

async function test(number_of_messages, break_between_messages) {
const websocket = new WebSocket(url...)

websocket.on('message', function incoming(data) {
console.log(getMessage("Received", data))
});

websocket.on('close', function(data) {
console.log('Disconnected!!!! ' + data.toString());
});

const opened = await connection(websocket)

//Wait 5 seconds
await sleep(5_000);

if (opened) {
for (i = 0; i < number_of_messages; i++) {

for (const chatId of chatIds) {
let content = i.toString() + " from " + user;
let msg = JSON.stringify({
"chatId": chatId,
"author": user,
"content": content
})
websocket.send(msg)

let message = getMessage("Sent", msg)
console.log(message)
}

await sleep(break_between_messages);
}

} else {
console.log("ERROR on Opening Connection")
return
}

// Wait 1 minute
await sleep(60_000);
websocket.close()
}
使用后端代码:
@Component
@ServerEndpoint(value = "/webSocket/{username}",
encoders = MessageRepresentationEncoder.class, decoders = MessageRepresentationDecoder.class)
public class MessagingSocket {
private Logger logger = LoggerFactory.getInstance();
private Session session;
private MessagingAPI messagingAPI = MessagingAPIFactory.createAPI();
private UserSocketRegistry userSocketRegistry = UserSocketRegistry.createRegistry();
private SessionUserRegistry sessionUserRegistry = SessionUserRegistry.createRegistry();

@OnOpen
public void onOpen(Session session, @PathParam("username") String username) {
this.session = session;
logger.log(LoggingType.INFO, "Started new session " + session.getId());
logger.log(LoggingType.INFO, username + " connected");

userSocketRegistry.addSessionForUser(this, username);
sessionUserRegistry.addSessionForUser(session, username);
}

@OnMessage //Allows the client to send message to the socket.
public void onMessage(MessageRepresentation messageRepresentation) {
logger.log(LoggingType.INFO, "Received " + messageRepresentation.toString());
messagingAPI.write(WriteMessage.from(UUID.fromString(messageRepresentation.chatId), messageRepresentation.author, messageRepresentation.content));
broadcastToChat(messageRepresentation);
}

private void broadcastToChat(MessageRepresentation message) {
final List<MessagingSocket> sockets = messagingAPI.getUsersConnectedToChat(UUID.fromString(message.chatId)).stream().filter(user -> userSocketRegistry.hasSocketFor(user.getName()))
.map(user -> userSocketRegistry.getSocketFor(user.getName())).collect(Collectors.toList());

logger.log(LoggingType.INFO, "Starting broadcast of " + message.content + " from " + message.author + " for " + String.join(",", messagingAPI.getUsersConnectedToChat(UUID.fromString(message.chatId)).stream().map(x -> x.getName()).collect(Collectors.toList())));
for (MessagingSocket messagingSocket : sockets) {
logger.log(LoggingType.INFO, "Broadcasting message" + message.content + " to " + messagingSocket.session.getId());
messagingSocket.sendMessage(message);

}
}

private void sendMessage(MessageRepresentation message) {
try {
this.session.getBasicRemote().sendObject(message);
} catch (IOException | EncodeException e) {
logger.log(LoggingType.ERROR, "Caught exception while sending message to Session Id: " + this.session.getId());
}
}

@OnClose
public void onClose(Session session) {
String user = sessionUserRegistry.getUserFor(session);
logger.log(LoggingType.INFO, "User " + user + " with session " + this.session.getId() + " disconnected ");
sessionUserRegistry.removeSession(session);
userSocketRegistry.removeUser(user);
}
}
和 MessageRepresentation 为:
public class MessageRepresentation {
public String chatId;
public String author;
public String content;

@Override
public String toString() {
return "MessageRepresentation{" +
"chatId='" + chatId + '\'' +
", author='" + author + '\'' +
", content='" + content + '\'' +
'}';
}
}
经过进一步调查,我得到以下异常:
java.lang.IllegalStateException: The remote endpoint was in state [TEXT_FULL_WRITING] which is an invalid state for called method
at org.apache.tomcat.websocket.WsRemoteEndpointImplBase$StateMachine.checkState(WsRemoteEndpointImplBase.java:1243)
at org.apache.tomcat.websocket.WsRemoteEndpointImplBase$StateMachine.textStart(WsRemoteEndpointImplBase.java:1205)
at org.apache.tomcat.websocket.WsRemoteEndpointImplBase.sendString(WsRemoteEndpointImplBase.java:191)
at org.apache.tomcat.websocket.WsRemoteEndpointImplBase.sendObject(WsRemoteEndpointImplBase.java:600)
at org.apache.tomcat.websocket.WsRemoteEndpointBasic.sendObject(WsRemoteEndpointBasic.java:74)
at presentation.frontend.websockets.server.MessagingSocket.sendMessage(MessagingSocket.java:64)
at presentation.frontend.websockets.server.MessagingSocket.broadcastToChat(MessagingSocket.java:57)
at presentation.frontend.websockets.server.MessagingSocket.onMessage(MessagingSocket.java:47)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.apache.tomcat.websocket.pojo.PojoMessageHandlerWholeBase.onMessage(PojoMessageHandlerWholeBase.java:80)
at org.apache.tomcat.websocket.WsFrameBase.sendMessageText(WsFrameBase.java:402)
at org.apache.tomcat.websocket.server.WsFrameServer.sendMessageText(WsFrameServer.java:119)
at org.apache.tomcat.websocket.WsFrameBase.processDataText(WsFrameBase.java:502)
at org.apache.tomcat.websocket.WsFrameBase.processData(WsFrameBase.java:301)
at org.apache.tomcat.websocket.WsFrameBase.processInputBuffer(WsFrameBase.java:133)
at org.apache.tomcat.websocket.server.WsFrameServer.onDataAvailable(WsFrameServer.java:82)
at org.apache.tomcat.websocket.server.WsFrameServer.doOnDataAvailable(WsFrameServer.java:171)
at org.apache.tomcat.websocket.server.WsFrameServer.notifyDataAvailable(WsFrameServer.java:151)
at org.apache.tomcat.websocket.server.WsHttpUpgradeHandler.upgradeDispatch(WsHttpUpgradeHandler.java:148)
at org.apache.coyote.http11.upgrade.UpgradeProcessorInternal.dispatch(UpgradeProcessorInternal.java:54)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:59)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:834)
java.lang.IllegalStateException:消息将不会发送,因为 WebSocket session 已关闭

最佳答案

我在这里可能不合时宜,但我认为这可能是由于包含无效 UTF8 或类似内容的消息。即畸形。
如果这听起来可能是原因,那么简单的解决方法是对 msg 进行编码。

        let msg = JSON.stringify({
"chatId": chatId,
"author": user,
"content": content
})
  let msg = unescape(encodeURIComponent(JSON.stringify({
"chatId": chatId,
"author": user,
"content": content
})));
然后在另一边解码...
JSON.parse(decodeURIComponent(escape( ... )))

关于javascript - WebSocket 关闭并出现协议(protocol)错误 1002,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65269411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com