@Override
public void connect(String url) throws Exception {
URI uri = new URI(url);
setConnected(false);
String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
final int port;
if (uri.getPort() == -1) {
if ("http".equalsIgnoreCase(scheme)) {
port = 80;
} else if ("https".equalsIgnoreCase(scheme)) {
port = 443;
} else {
port = -1;
}
} else {
port = uri.getPort();
}
if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) {
Notifications.Bus.notify(
new Notification(
"Websocket Client",
"Unable to connect",
"Only WS(S) is supported.",
NotificationType.ERROR)
);
return;
}
EventLoopGroup group = new NioEventLoopGroup();
try {
WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(
uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders());
WebSocketClientHandler webSocketClientHandler = new WebSocketClientHandler(handshaker);
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline();
p.addLast(
new HttpClientCodec(),
new HttpObjectAggregator(8192),
webSocketClientHandler);
}
});
channel = bootstrap.connect(uri.getHost(), port).sync().channel();
webSocketClientHandler.handshakeFuture().sync();
setConnected(true);
for (; ; );
} finally {
group.shutdownGracefully();
setConnected(false);
}
}
WebSocketClient.java 文件源码
java
阅读 22
收藏 0
点赞 0
评论 0
项目:idea-websocket-client
作者:
评论列表
文章目录