jetty websocket server: Send customer status code based on application logic

I am writing a Websocket server using Jetty.

My handler code:

public class WebSocketServerHandler {

    @OnWebSocketClose
    public void onClose(int statusCode, String reason) {
        System.out.println("Close: statusCode=" + statusCode + ", reason=" + reason);

    }

    @OnWebSocketError
    public void onError(Throwable t) {
    }

    @OnWebSocketConnect
    public void onConnect(Session session) {

    }

    @OnWebSocketMessage
    public void onMessage(Session session, String message) {
    }

    @OnWebSocketMessage
    public void onBinaryMethod(Session session, byte data[], int offset, int length) {

    }
}

One of my requirement is to send custom status code based on business logic insde onBinaryMethod
eg: Send 1001 as status code for timeout (Jetty already support this)

I am not sure where to set these status codes. I have tried following but that doesn't seems to work.

Session().getUpgradeResponse().setStatusCode();

WebSockets

Here is the RFC regarding the status codes of WebSocket.

During the communication with the socket You are not supposed to send such information in status codes. Send a message instead with the information which is needed by the client.

If you happen to be interested in closing codes you can supply this information on the Session object as follows:

session.close(new CloseReason(YOUR_NUMBER, "Your reason")); 

REST

If You rely on those codes use REST services , there are a lot of options there:

  • Throw a specific exception
  • Use response builder and return the response
  • Inject the context
  • I think the easiest way to achieve Your goal is to use setStatus(int) :

    @Context 
    HttpServletResponse response;
    
    @Path("/method")
    public void onBinaryMethod() {
        int statusCode = 200;
        //SOME CODE
        response.setStatus(statusCode);
    }
    

    Here is a nice answer listing a lot of possible solutions:

    https://stackoverflow.com/a/22869076/4823977

    链接地址: http://www.djcxy.com/p/45590.html

    上一篇: 如何在没有任何HTML主体的情况下为RESTful做响应404?

    下一篇: jetty websocket服务器:根据应用程序逻辑发送客户状态码