全球共享整数

时间:2013-11-22 16:27:36

标签: java netty

我正在学习Netty并且我正在尝试实现一个简单的计数器,其中所有客户端共享Integer并且他们输入一个数字并且Integer值增加号。

这是我的代码:

Server.java

package nettyincvalue;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Server {

    private int port;
    private Integer value;

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

    public void run(){

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {

            ServerBootstrap server = new ServerBootstrap();

            server.group(bossGroup, workerGroup)
                  .channel(NioServerSocketChannel.class)
                  .childHandler(new ServerInit(this.value))
                  .option(ChannelOption.SO_BACKLOG, 128)
                  .childOption(ChannelOption.SO_KEEPALIVE, true);


            ChannelFuture f = server.bind(port).sync();

            f.channel().closeFuture().sync();


        } catch (InterruptedException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }

    public static void main(String[] args) {
        new Server(12345).run();
    }

}

ServerInit.java

package nettyincvalue;

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

public class ServerInit extends ChannelInitializer<SocketChannel> {

    private Integer value;

    public ServerInit(Integer value) {
        this.value = value;
    }

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {

        ChannelPipeline pipeline = ch.pipeline();

        pipeline.addLast(new StringDecoder());
        pipeline.addLast(new ServerHandler(this.value));

    }

}

ServerHandler.java

package nettyincvalue;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class ServerHandler extends ChannelInboundHandlerAdapter {

    private Integer value;

    public ServerHandler(Integer value) {
        this.value = value;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        String s = (String) msg;

        try {

            Integer i = Integer.parseInt(s.substring(0, s.length() - 1));
            this.value += i;
            System.out.println("Value its now: " + this.value);

        } catch (NumberFormatException n) {
            System.out.println("Not a number received");
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.err.println(cause.getMessage());
        ctx.close();
    }
}

单独地,它的工作,当客户端通过nc输入一个数字时它会递增,但它不是全局的,我的意思是当一个不同的客户端启动时,计数器将其设置为0。

1 个答案:

答案 0 :(得分:3)

您的变量没有正确的同步;通常应该声明它volatile以确保所有线程都看到更新的值,并且您需要同步您正在使用它的块。但是,在您的情况下,使用AtomicInteger将更简单,更有效。