Tuesday 28 February 2017

Using Netty in Java

Usuful links:
1. https://en.wikipedia.org/wiki/Netty_(software)
2. https://habrahabr.ru/post/277695/

NettyClient.java:

package socketclient.netty;

import com.thetransactioncompany.jsonrpc2.JSONRPC2Request;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import socketclient.common.ClientRequest;

/** * Created by Mansurjon on 2/9/2017. */

public class NettyClient<T> {
    protected final int SOCKET_WAIT_TIME = 100;
    protected final int SOCKET_LOOP_MAX_COUNT = 5;
    private  String host;
    private  int port;
    private Channel channel;
    private Boolean isOpen = false;
    private EventLoopGroup group;
    public Channel getChannel() {
        return channel;
    }
    public NettyClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public boolean start() {
        group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new NettyClientInitializer());
        try {
            channel = bootstrap.connect(host, port).sync().channel();
        } catch (InterruptedException e) {
            return false;
            //e.printStackTrace();        }
        isOpen = channel.isActive();
        return isOpen;
    }
    public String ececute(ClientRequest clientRequest){
        if (isOpen){
            JSONRPC2Request request=new
                JSONRPC2Request(clientRequest.getMethodName(),
                clientRequest.getReqParams(),clientRequest.getRequestID());
            this.channel.write(request.toString() + "\r\n");
            int loopTimeout = 0;
            while (NettyClientHandler.jsonResponse.equals("")&&
                            loopTimeout<SOCKET_LOOP_MAX_COUNT){
                try {
                    loopTimeout++;
                    Thread.sleep(SOCKET_WAIT_TIME);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            this.channel.flush();
            group.shutdownGracefully();
            return NettyClientHandler.jsonResponse;
        }
        return "";
    }

    public EventLoopGroup getGroup() {
        return group;
    }

    public void close(){
        if (!isOpen){
            this.channel.flush();
            this.channel.close();
            this.channel.close();
            group.shutdownGracefully();
            isOpen = false;group = null;
        }
    }
}


NettyClientHandler.java:

package socketclient.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundMessageHandlerAdapter;

public class NettyClientHandler extends ChannelInboundMessageHandlerAdapter<String> {
    public static String jsonResponse ="";
    @Override    public void endMessageReceived(ChannelHandlerContext ctx) throws Exception {
        //System.out.println("Javob olindi");    }

    @Override    public void messageReceived(ChannelHandlerContext ctx, String jsonString) 
                                              throws Exception {
        jsonResponse = jsonString;
    }
}

NettyClientInitializer.java:

package socketclient.netty;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class NettyClientInitializer extends ChannelInitializer<SocketChannel> {

    @Override    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, 
                                            Delimiters.lineDelimiter()));
        pipeline.addLast("decoder", new StringDecoder());
        pipeline.addLast("encoder", new StringEncoder());
        pipeline.addLast("handler", new NettyClientHandler());

    }
}






Netty Serverni quyidagi ko'rinishda yaratish mumkin:

Server.java:


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/** * Created by Mansurjon on 2014/6/28. */

public class Server {
    private static final int PORT=1010;
    public static void main(String[] args) throws InterruptedException {
        new Server(PORT).run();
    }
    private final  int port;

    public Server(int port){
        this.port = port;
    }

    public void run()  {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            System.out.println("Port:"+port);
            System.out.println("Our server running normally!:)");
            ServerBootstrap bootstrap = new ServerBootstrap()
                    .group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ServerInitializer());
            ChannelFuture future = bootstrap.bind(port).sync();
            future.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}


ServerHandler.java:

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundMessageHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import common.MethodParser;

/** * Created by Mansurjon on 2014/6/28. */

public class ServerHandler extends ChannelInboundMessageHandlerAdapter<String> {

    private static final ChannelGroup channels = new DefaultChannelGroup();

    @Override    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    }

    @Override    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
    }

    @Override    public void messageReceived(ChannelHandlerContext ctx, String jsonString) 
                                                           throws Exception {
        System.out.println("-----------------");
        System.out.println("NettyClient info:"+ctx.channel().remoteAddress());
        System.out.println("Request from client:"+jsonString);
        String result = MethodParser.invoke(jsonString);
        System.out.println("Response to client:"+result);
        System.out.println("-----------------");

        Channel incoming = ctx.channel();
        incoming.write(result+"\r\n");
        incoming.flush();
        incoming.close();
        incoming.closeFuture();
    }

}

ServerInitializer.java:

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/** * Created by Mansurjon on 2014/6/28. */

public class ServerInitializer extends ChannelInitializer<SocketChannel> {

    @Override    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();

        pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, 
                                               Delimiters.lineDelimiter()));
        pipeline.addLast("decoder", new StringDecoder());
        pipeline.addLast("encoder", new StringEncoder());
        pipeline.addLast("handler", new ServerHandler());
    }

}



Test qilish uchun:
ClientTest.java

package socketclient;

import socketclient.common.ClientRequest;
import socketclient.common.GetAvlDataRequest;
import socketclient.common.GetObjectListRequest;
import socketclient.common.ServerInfo;

/** * Created by Mansurjon on 2/17/2017. */

public class ClientTest {
    public static void main(String[] args) {
        ServerInfo serverInfo = new ServerInfo.ServerInfoBuilder("localhost",1010).build();
        GetObjectListRequest getObjectListRequest = new GetObjectListRequest(10L,"uz",
"1789uqw-19788912",100L);
        GetAvlDataRequest getAvlDataRequest = new GetAvlDataRequest(9L,"en","avl data");
        ClientRequest clientRequest = new ClientRequest("getObjectList",getObjectListRequest);
        Client client1 = new Client.ClientBuilder(serverInfo).
                                                 setRequest(clientRequest).execute();
        System.out.println("this is server resp.:"+client1.getResponse());
    }
}


No comments:

Post a Comment

Note: only a member of this blog may post a comment.

Tasks and Threads

  Differences Between Task And Thread: 1. The Thread class is used for creating and manipulating a thread in Windows.  2. A Task represents ...