Search code examples
javasocketswebsocketjettyjetty-9

How to upgrade an HTTPConnection to a WebsocketConnection in Jetty 9?


I've been reading the documentation of Jetty 9 and they seemed to have gotten rid of the Jetty Socket Connector. So now we have a general ServerConnector and we "upgrade" and HTTPConnection to a WebSocket connection. I've read the documentation about Socket vs WebSocket (Difference between socket and websocket?) and everything linked in that answer. My question is:

1) How do I do the upgrade from HTTPConnection to WebSocket connection? Could someone provide some sample code please?

2) I'm building a desktop app that connects to the server I am writing as well. I need to simulate a TCP connection, will the WebSocketConnection work for me? I ask this because I mostly hear about WebSockets in the context of Browsers and I want to make sure that it is something that I can use in my client app.

Thank you!


Solution

  • WebSocket is not a naked TCP connection, lets get that out of the way first.

    It is a framing protocol, for TEXT, BINARY, and CONTROL frames (Control frames are tiny frames for things like PING, PONG, CLOSE)

    It would be best to read the official protocol spec to better understand this: RFC-6455

    There is no requirement for the client to be a browser, the client can be any application capable of making a web request.

    If this fits your need, then read on.

    Jetty itself provides a WebSocket server and WebSocket client implementation using a native API and also supporting the javax.websocket standard (aka JSR-356).

    As for the Jetty WebSocket Server, it internally performs the upgrade within the org.eclipse.jetty.websocket.server.WebSocketFactory upgrade() private method.

    If you choose to experiment with WebSocket on Jetty, read the documentation and choose from either the native API or javax.websocket API, either one will work.

    If you want to understand the difference in those APIs, there's actually a different question/answer for that.