netty websocket client
netty4 websocket client(带返回结果的客户端)
网上更多的基于netty的websocket服务端的实现,客户端更多的是html,本文介绍自己实现websocket的client,并返回异步返回结果的数据,方便业务逻辑调用。
pom依赖
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.35.Final</version>
</dependency>
ClientInitializer
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import java.util.concurrent.CountDownLatch;
public class ClientInitializer extends ChannelInitializer<SocketChannel> {
private CountDownLatch latch;
public ClientInitializer(CountDownLatch latch) {
this.latch = latch;
}
private WebSocketClientHandler handler;
@Override
protected void initChannel(SocketChannel sc) throws Exception {
handler = new WebSocketClientHandler(latch);
ChannelPipeline p = sc.pipeline();
p.addLast(new ChannelHandler[]{new HttpClientCodec(),
new HttpObjectAggregator(1024*1024*10)});
p.addLast("websocketHandler", handler);
}
public String getServerResult(){
return handler.getResult();
}
public void resetLathc(CountDownLatch latch) {
handler.resetLatch(latch);
}
public void setHandler(WebSocketClientHandler handler){
this.handler = handler;
}
WebSocketClientHandler
import io.netty.channel.*;
import io.netty.handler.codec.http.Ful