gpt4 book ai didi

javascript - Websocket.onmessage 没有触发

转载 作者:行者123 更新时间:2023-11-30 19:12:48 25 4
gpt4 key购买 nike

我尝试通过 JS-WebSocket 在 Java WebsocketServer ( https://github.com/TooTallNate/Java-WebSocket) 与网页之间进行通信。

我的 JS-Websocket:

window.websocket = new WebSocket("ws://localhost:8000");
window.websocket.onopen = () => {
window.websocket.send("Hello")
}




window.websocket.onmmessage = function(event) {
alert('Hi');

console.log(event.data);
}

和我的 Java-Websocket-Server:

package test;

import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.HashSet;
import java.util.Set;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

public class testsocket extends WebSocketServer {


private static int TCP_PORT = 9000;

private Set<WebSocket> conns;

public testsocket() throws UnknownHostException {
super(new InetSocketAddress(TCP_PORT));
conns = new HashSet<>();

}

@Override
public void onOpen(WebSocket conn, ClientHandshake handshake) {
conns.add(conn);
System.out.println("New connection from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());

}

@Override
public void onClose(WebSocket conn, int code, String reason, boolean remote) {

}

@Override
public void onMessage(WebSocket conn, String message) {
System.out.println(message);

String s2send = "hello";
System.out.println(s2send);
conn.send(s2send);


}

@Override
public void onError(WebSocket conn, Exception ex) {
ex.printStackTrace();
if (conn != null) {
conns.remove(conn);
// do some thing if required
}

}

}

所以我的 Java-Websocket 打印“Hello”,所以我可以从 JS 到 Java 进行通信,但另一方面我的 Websocket 既没有显示警报也没有在控制台打印,所以我假设 onmessage 没有触发

最佳答案

如果您确定,您的 java ws 服务器正在工作......那么

有错别字!事件监听器应该是 window.websocket.onmessage window.websocket.onmmessage。两个“m”:)

window.websocket = new WebSocket("ws://localhost:8000");
window.websocket.onopen = () => {
window.websocket.send("Hello");
};

window.websocket.onmessage = function(event) {
alert("Hi");

console.log(event.data);
};

关于javascript - Websocket.onmessage 没有触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58304250/

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