Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static boolean connect(Host host, String message, int mode) throws Exception {
- EventLoopGroup group = new NioEventLoopGroup();
- try {
- Bootstrap clientBootstrap = new Bootstrap();
- clientBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 100);
- clientBootstrap.group(group);
- clientBootstrap.channel(NioSocketChannel.class);
- clientBootstrap.remoteAddress(new InetSocketAddress(host.getIp(), host.getPort()));
- clientBootstrap.handler(new ChannelInitializer<SocketChannel>() {
- protected void initChannel(SocketChannel socketChannel) {
- //TODO, TIMEOUT BILGISI ILE DOLDUR BURAYI
- //socketChannel.pipeline().addLast(new ReadTimeoutHandler(1));
- //socketChannel.pipeline().addLast("idleStateHandler", new IdleStateHandler(2, 2, 4));
- socketChannel.pipeline().addLast(new FalconClientHandler(host, message, mode));
- }
- });
- ChannelFuture channelFuture = clientBootstrap.connect().sync();
- //TODO I NEED TO CATCH IT SOMEWHERE IN HERE
- channelFuture.channel().closeFuture().sync();
- return true;
- } catch (Exception e) {
- System.err.println("Connection timed out --> " + e);
- host.setActive(false); //connection kurulamadı demektir. Bir sonraki mesaj geldiğinde bu hostun açılıp açılmadığı denenecek.
- return false;
- } finally {
- group.shutdownGracefully().sync();
- if (mode == 0) { //arka planda sunucu hep ayakta olmalı. Mode 0 da asla bağlantı kesilmemeli. Kesiliyorsa host kapanmıştır.
- host.setActive(false);
- return false;
- }
- }
- }
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)throws Exception {
- cause.printStackTrace();
- //CLOSE CONNECTION AND I HAVE TO PASS THE INFORMATION WHY CONNECTION CLOSED
- ctx.close();
- }
- @Override
- public void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf in) {
- InetSocketAddress socketAddress = (InetSocketAddress) channelHandlerContext.channel().remoteAddress();
- InetAddress inetaddress = socketAddress.getAddress();
- String ipAddress = inetaddress.getHostAddress(); // IP address of client
- TCPHandshakeMessage tcpMessage;
- byte[] signal;
- String input = in.toString(CharsetUtil.US_ASCII);
- /*
- * mode 0 -> Amaç sunucuların ayakta olup olmadığını anlamak
- * mode 1 -> Amaç sunuculara mesaj göndermek
- * */
- if(this.mode == 1){ //MODE 1 BAŞLANGICI
- //I WRITE THIS ON PURPOSE
- double x = 12 / 0;
- System.err.println("MESSAGE SENT TO " + message + " IP : " + ipAddress);
- this.host.setActive(true);
- //TODO TCP MESSAGE SINIFINI KULLAN
- signal = message.getBytes();
- sendMessage(channelHandlerContext, signal);
- /*try {
- }catch (Exception e){
- System.out.println("An Error Occured " + e);
- }finally {
- channelHandlerContext.channel().close();
- }*/
- }
- }
Add Comment
Please, Sign In to add comment