如何在WebSockets Java中启动服务器端消息?

时间:2018-01-04 10:49:57

标签: javascript java websocket

我在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

感谢任何帮助。感谢。

1 个答案:

答案 0 :(得分:1)

我的问题很容易回答。我需要做的就是:

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