如何解决为什么我的 Java Vertx 项目没有使用 SockJS 连接到 web 项目?
当我尝试使用简单的广播消息示例在 Java Vertx 上实现 SockJS 时,我的问题出现了,我只收到“欢迎使用 SockJS 消息!”在服务器端,但前端和后端似乎没有连接。我是 Vertx 和 SockJS 的新手,因此非常感谢任何帮助。
这是我的index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Push Notifications</title>
<script src="client.js"> </script>
<script src="https://unpkg.io/sockjs-client@1.5.0/dist/sockjs.min.js"></script>
</head>
<body>
<h1>Push Notifications With Vertx</h1>
<script>
var sock;
function openSock() {
sock = new SockJS('http://localhost:8080/myapp');
sock.onopen = function() {
sock.onopen = function() {
console.log('open');
};
sock.onmessage = function(e) {
console.log('message',e.data);
};
sock.onevent = function(event,message) {
console.log('event: %o,message:%o',event,message);
return true; // in order to signal that the message has been processed
};
sock.onerror = function(e) {
console.error(e);
}
sock.onunhandled = function(json) {
console.log('this message has no address:',json);
};
sock.onclose = function() {
console.log('close');
};
sock.send('test');
}
}
openSock();
</script>
</body>
</html>
这是我的MainVerticle.java
package com.bcm.vertxmvn;
import io.vertx.core.AbstractVerticle;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.sockjs.SockJSHandler;
import io.vertx.ext.web.handler.sockjs.SockJSHandlerOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MainVerticle extends AbstractVerticle {
private static final Logger LOGGER = LoggerFactory.getLogger(MainVerticle.class);
@Override
public void start() {
Router router = Router.router(vertx);
SockJSHandlerOptions options = new SockJSHandlerOptions()
.setHeartbeatInterval(2000);
SockJSHandler sockJSHandler = SockJSHandler.create(vertx,options);
router.mountSubRouter("/myapp",sockJSHandler.socketHandler(sockJSSocket -> {
// Just echo the data back
sockJSSocket.handler(sockJSSocket::write);
}));
vertx.createHttpServer().requestHandler(router).listen(8080);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。