Tomcat WebSocket关闭连接

时间:2019-06-07 12:03:45

标签: java tomcat websocket

我在Tomcat上运行简单的Websocket服务器:

package server.ws;

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




@ServerEndpoint("/websocketendpoint")

public class WsServer {

    @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();
    }

}

连接到我的服务器的客户端抱怨Tomcat在发送回声后关闭了会话。回声后如何使服务器不关闭连接?

1 个答案:

答案 0 :(得分:1)

我不确定,但是我猜onMessage没有返回值。 对我来说,以下代码可以正常工作,我有任何问题

@OnMessage
public void message(final String message, final javax.websocket.Session session) throws IOException {
    for (final Session s : session.getOpenSessions()) {
        final Basic endpoint = s.getBasicRemote();
        endpoint.sendText(message);
    }
}