com.fastchar.socket.client.tcp.FastTcpSocketClient Maven / Gradle / Ivy
package com.fastchar.socket.client.tcp;
import com.fastchar.socket.client.websocket.FastWebSocketClientChannelHandler;
import com.fastchar.socket.client.websocket.FastWebSocketConvertHeaderHandler;
import com.fastchar.socket.interfaces.IFastTcpSocketClientListener;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketClientCompressionHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import java.net.URI;
public class FastTcpSocketClient {
private static final EventLoopGroup EVENT_LOOP_GROUP = new NioEventLoopGroup();
public static void closeAll() {
EVENT_LOOP_GROUP.shutdownGracefully();
}
public Channel newTcpSocket(final String url, final IFastTcpSocketClientListener iFastTcpSocketClientListener) {
try {
final URI uri = new URI(url);
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(EVENT_LOOP_GROUP)
.option(ChannelOption.SO_KEEPALIVE, true)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer() {
@Override
protected void initChannel(SocketChannel ch) {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(
new LoggingHandler(LogLevel.INFO),
new FastTcpSocketClientChannelHandler(iFastTcpSocketClientListener));
}
});
ChannelFuture channelFuture = bootstrap.connect(uri.getHost(), uri.getPort()).sync();
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}