我在运行Java EE应用程序时遇到问题。我有服务器edpoint的代码:
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.context.ApplicationScoped;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
@ApplicationScoped
@ServerEndpoint(
value = "/model"
)
public class ModelWebSocket {
private final ModelHandle model = new ModelHandle();
@OnOpen
public void onOpen(Session session) throws IOException {
}
@OnError
public void onError(Throwable error) {
/// put model back to pool, log erros
}
// This code never calls,
@OnMessage
public void onMessage(String message, Session session) {
//TODO: Add decoders/encoders to annotations
try {
ModelInputData inputData = new ModelInputDataDecoder().decode(message);
double input = inputData.getInput();
double timespan = inputData.getTimespan();
model.setInput(input);
ModelProcessData process = model.getOuptput(timespan);
try {
session.getBasicRemote().sendText(
new ModelProcessDataEncoder().encode(process)
);
} catch (IOException | EncodeException ex) {
Logger.getLogger(ModelWebSocket.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (DecodeException ex) {
Logger.getLogger(ModelWebSocket.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
And the following stub for a client stub in javascript:
<!DOCTYPE html>
<!--
This is a test
-->
<html>
<head>
<title>Test</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<!-- insert the main script here -->
<script type ="text/javascript">
//copied from https://learn.javascript.ru/websockets
var socket = new WebSocket(
"ws://localhost:8080/SimulatorWeb/model"
);
socket.onopen = function () {
alert("Connection OK");
};
socket.onclose = function (event) {
if (event.wasClean) {
alert('Connection closed');
} else {
alert('Connection interrupted'); // например, "убит" процесс сервера
}
alert('Code: ' + event.code + ' redason: ' + event.reason);
};
socket.onmessage = function (event) {
alert("Data accepted " + event.data);
};
socket.onerror = function (error) {
alert("Error " + error.message);
};
function send(){
socket.send("dummy");
}
</script>
<button type="button" onclick="send();" >Send</button>
</body>
</html>
客户端似乎发送消息,但OnMessage从未被截获。 当我启动Glassfish 4.1.1时,我有以下警告:
我花了很多时间调试,但我仍然无法找到问题......我使用的是Java 8 SDK和NetBeans IDE。
(在代码中我没有使用解码器/编码器,因为我认为它们是问题并将它们从ServerEnpoint中删除)
答案 0 :(得分:0)
我不知道Glassfish的问题是什么......我转向Tomcat并手动添加到WEB_INF / lib我需要的所有外部库(在我的例子中为javax.json)。 Tomcat似乎没有给出原始代码的警告,一切正常。