gpt4 book ai didi

java - 无法通过 websocket 连接进行连接

转载 作者:行者123 更新时间:2023-11-29 05:24:50 27 4
gpt4 key购买 nike

我正在尝试在我的项目中创建一个简单的 Websocket 连接。

Java代码:

@ServerEndpoint("/echo")
public class EchoEndpoint {
@OnMessage
public void onMessage(Session session,String message){
try{
System.out.println(message);
}
catch(Exception e){
System.out.println(e.getMessage());
}
}

}

html 和 javascript 代码:

<button type="button" onclick="WebSocketTest()">Send</button>
<script type="text/javascript">
function WebSocketTest()
{

alert("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://localhost:8080/echo");
ws.onopen = function()
{
// Web Socket is connected, send data using send()
ws.send("Message to send");
alert("Message is sent...");
};
ws.onmessage = function (evt)
{
var received_msg = evt.data;
alert("Message is received...");
};
ws.onclose = function()
{
// websocket is closed.
alert("Connection is closed...");
};


}
</script>

按下按钮后出现错误WebSocket connection to 'ws://localhost:8080/echo' failed: Error during WebSocket handshake: Unexpected response code: 404

Jboss Wildfly8 被用作应用服务器。

有什么想法吗?或任何工作示例?

最佳答案

这是因为你把路径放错了:

var ws = new WebSocket("ws://localhost:8080/echo");

如果您的应用程序被打包为例如:websocketapp.war(或者如果您在 websocketapp 上设置上下文路径)那么你应该使用:

var ws = new WebSocket("ws://localhost:8080/websocketapp/echo");

关于java - 无法通过 websocket 连接进行连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23066125/

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