In the use of the WebSocket server in Netty, the usage of WebSocket in Netty is introduced. After completion, we have carried out related tests in the browser. Here we are using Netty to implement a simple WebSocket client, combined with the previous The server communicates.
In use Netty achieve Http server and client later, we realized the service side, followed by also using Netty uses a simple client, which is used to launch a DefaultFullHttpRequest provided by Netty Http request, then read the server returns News.
Here we also modify according to the Http client previously implemented, and then implement a client that implements WebSocket. First, we encapsulate a WebSocketClientHandshaker with a connection address on the client (the uri, V13, etc. are related parameters of WebSocket), will It is passed to WebSocketClientHandler, which is implemented by ourselves
Then it is the standard Netty startup, which adds the related WebSocket processing in the Pipeline, which needs to judge about the SSL processing, and our own WebSocketClientHandler
After waiting for the client to start, we can send the corresponding message in the console as follows:
Next, take a look at the WebSocketClientHandler that we have implemented. When the channel is established, a handshake is performed.
Then after the handshake is complete, it is to read the relevant messages sent by our server, but when reading the messages, because the handshake may be longer, the handshake action has not ended, we need to judge whether the handshake is completed
When the handshake action is completed, our server should receive no more Http requests. Here we can handle WebSocket related requests, but in the use of WebSocket server in Netty , we have related Http requests, such as browsing The browser requests related html pages, etc. Here, we do not need related html pages, so we can simply ignore its Http request and then process the related WebSocket request.
Here our client's has also been handled. Here we will conduct a joint test of the previously implemented server and the client here, as follows:
Then we can also conduct related tests in conjunction with the browser, as follows: