gpt4 book ai didi

java - Websocket 在打开后关闭连接

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

我有以下 websockets 测试 html 页面

<!DOCTYPE html>
<html>

<head>
<title>Apache Tomcat WebSocket Example</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
var ws = null;
var target = 'ws://some_ip_addr:8080/gameserv-1.0/endpoint';

function connect() {
if ('WebSocket' in window) {
ws = new WebSocket(target);
} else if ('MozWebSocket' in window) {
ws = new MozWebSocket(target);
} else {
alert('WebSocket is not supported by this browser.');
return;
}
ws.onopen = function() {
log('Info: WebSocket connection opened.');
};
ws.onmessage = function(event) {
log('Received: ' + event.data);
};
ws.onclose = function() {
log('Info: WebSocket connection closed.');
};
}

function disconnect() {
if (ws != null) {
ws.close();
ws = null;
}
// setConnected(false);
}

function log(message) {
$("#mydiv").append($("<p>").text(message));
}

function testButtonSend() {
var message = {
'commandType': 'TEST',
'command': 'AUCTIONLIST'
};
ws.send(message);
}

$(document).ready(function() {
connect();
});
</script>
</head>

<body>
<div id="mydiv">
<input type="button" onclick="testButtonSend()">
</div>
</body>

</html>

负责这个websocket的java类是:

@ServerEndpoint("/endpoint")
public final class Websocket {

Gson gson = new Gson();
private boolean connectionOpen;
private Session session;

public Websocket(int byteBufferMaxSize, int charBufferMaxSize) {
super();
setConnectionOpen(false);
}

@OnOpen
public void onOpen(final Session session, EndpointConfig config) {
this.connectionOpen = true;
this.session = session;
}

@OnClose
public void close(Session session,
CloseReason reason) {
this.connectionOpen = false;
this.session = null;
}

@OnMessage
public void onTextMessage(Session session, String message) throws IOException {
MessageFromClientAPI messageFromClient = gson.fromJson(message, MessageFromClientAPI.class);

Integer pID = messageFromClient.getpID();
....
}

public boolean send(MessageToClientAPI message) {
if (!connectionOpen)
return false;
try {
session.getBasicRemote().sendText(gson.toJson(message));
} catch (IOException e) {
e.printStackTrace();
}
return true;
}

public boolean isConnectionOpen() {
return connectionOpen;
}

public void setConnectionOpen(boolean connectionOpen) {
this.connectionOpen = connectionOpen;
}
}

问题是连接打开后立即关闭。此外,调试器不会在 onOpen 方法(以及任何其他方法)上停止。

错误是什么?

最佳答案

问题已解决。其原因在于构造函数中。这是不正确的。我刚刚删除了它,现在它可以工作了。

关于java - Websocket 在打开后关闭连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29211809/

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