【发布时间】:2018-01-04 10:49:57
【问题描述】:
我在 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
感谢任何帮助。谢谢。
【问题讨论】:
-
您的问题遗漏了一些信息:您想在什么条件下发送消息?收到另一条消息后?在某事件上?无论如何,对于基本答案,link to a tutorial (section 4.4) 就可以了:
session.getBasicRemote().sendText(“yahooo!”); -
我想在事件发生时发送消息。
-
根据您的回答,这是一个简单的东西...顺便说一下,如果您打算在您的
ServerEndpoint中使用 CDI 事件 (@Observes),请注意,如果没有 websocket客户端已连接,您可能会遇到一些问题。在我的项目中,我们使用会话处理程序类来处理 CDI 事件 -
在我有限的经验中,我还没有遇到过 CDI 事件……你能详细说明一下吗?任何可以对此事有所启发的具体例子都会很棒......谢谢
-
如果你有空,我宁愿聊天:chat.stackoverflow.com/rooms/162727/…(我是聊天新手...)
标签: javascript java websocket