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());
    }
}


Sunday, 26 February 2017

LinkedBlockingQueue in Java Example program

Ma'lumki LinkedBlockingQueue JDK 1.5dan boshlab foydalaniladi.
"Queue" so'zi navbat("Очередь") ma'nosini bildiradi.  LinkedBlockingQueue java.util.concurrent paketiga tegishli. 
BlockingQueue ga element qo'shish uchun put, add yoki offer ishlatiladi. BlockingQueue dan birinchi turgan elementni "olish" uchun take(), poll() yoki remove() ishlatiladi.
Misollar:

Misol #1: BlockingQueue sinfi ob’ektini yaratish va unga qiymat berish

BlockingQueue<String> myQueue = new LinkedBlockingQueue<>(10);
try {

    for (int i=1;i<=10;i++)

        myQueue.put("m"+i);

} catch (InterruptedException e) {

    e.printStackTrace();

}
 
Misol #2: 1-misoldagi myQueue ob’ekti qiymatlarini 2ta thread(поток) yordamida navbatma-navbat o’qish.

Bunda Threadlar tezligi turlicha:

package linkedblockingqueue;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/** * Created by Mansurjon on 2/16/2017. */
public class Sample3 {

    private static BlockingQueue<String> myQueue = new LinkedBlockingQueue<>(10);
    public static void main(String[] args) {
        try {
            for (int i=1;i<=10;i++)
                myQueue.put("m"+i);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Our queue:"+ myQueue);
        new Thread(new Runnable() {
            @Override            public void run() {

                while (!myQueue.isEmpty())
                    try {
                        String data = myQueue.take();
                        System.out.println("Thread 1:"+data);
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

            }
        },"myThread1").start();

        new Thread(new Runnable() {
            @Override            public void run() {
                while (!myQueue.isEmpty())
                    try {
                        String data = myQueue.take();
                        System.out.println("Thread 2:"+data);
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

            }
        },"myThread2").start();
}}

-------------------------
Natija:
Our queue:[m1, m2, m3, m4, m5, m6, m7, m8, m9, m10]
Thread 1:m1
Thread 2:m2
Thread 1:m3
Thread 1:m4
Thread 1:m5
Thread 1:m6
Thread 1:m7
Thread 2:m8
Thread 1:m9
Thread 1:m10

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 ...