gpt4 book ai didi

javascript - 如何在 WebSockets Java 中发起服务器端消息?

转载 作者:行者123 更新时间:2023-12-02 11:47:40 25 4
gpt4 key购买 nike

我正在 Java 中使用 javax.websocket API。我正在使用 Jetty 服务器和 Javascript 作为客户端。如何从服务器发起 sendMessage?

详细信息:我使用 jetty-maven-plugin 9.4.8.v20171121。

服务器端依赖项:org.eclipse.jetty.websocket - websocket-server 和 javax-websocket-server-impl。

这是我的服务器代码:

package com.trice.server.web;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/WebSocketTestServlet")
public class WebSocketTestServlet {

@OnOpen
public void onOpen(){
System.out.println("Open Connection ...");
}

@OnClose
public void onClose(){
System.out.println("Close Connection ...");
}

@OnMessage
public String onMessage(String message){
System.out.println("Message from the client: " + message);
String echoMsg = "Echo from the server : " + message;
return echoMsg;
}

@OnError
public void onError(Throwable e){
e.printStackTrace();
}
}

和客户端代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Tomcat WebSocket</title>
</head>
<body>
<form>
<input id="message" type="text">
<input onclick="wsSendMessage();" value="Echo" type="button">
<input onclick="wsCloseConnection();" value="Disconnect" type="button">
</form>
<br>
<textarea id="echoText" rows="5" cols="30"></textarea>
<script type="text/javascript">
var webSocket = new WebSocket("ws://localhost:8080/WebSocketTestServlet");
var echoText = document.getElementById("echoText");
echoText.value = "";
var message = document.getElementById("message");
webSocket.onopen = function(message){ wsOpen(message);};
webSocket.onmessage = function(message){ wsGetMessage(message);};
webSocket.onclose = function(message){ wsClose(message);};
webSocket.onerror = function(message){ wsError(message);};
function wsOpen(message){
echoText.value += "Connected ... \n";
}
function wsSendMessage(){
webSocket.send(message.value);
echoText.value += "Message sent to the server : " + message.value + "\n";
message.value = "";
}
function wsCloseConnection(){
webSocket.close();
}
function wsGetMessage(message){
echoText.value += "Message received from to the server : " + message.data + "\n";
}
function wsClose(message){
echoText.value += "Disconnect ... \n";
console.log("disconnect", message);
}

function wsError(message){
echoText.value += "Error \n";
console.log("error", message);
}
</script>
</body>
</html>

引用link

感谢任何帮助。谢谢。

最佳答案

我的问题有一个非常简单的答案。我需要做的就是:

session.getBasicRemote().sendText("Some string");

关于javascript - 如何在 WebSockets Java 中发起服务器端消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48093633/

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