来源网络,以备不时之需

  • 首先引入jar包
    由于不是很了解,直接引入netty-all-4.1.9.Final.jar和netty-all-4.1.9.Final-sources.jar这两个包,
    需要自定义的可以去官网下载完整
    官网地址:http://netty.io/

    代码实例:

  • nettyServer

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    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;
    public class nettyServer {

    /**
    * 服务端监听的端口地址
    */
    private static final int portNumber = 18632;

    public static void main(String[] args) throws InterruptedException {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup);
    b.channel(NioServerSocketChannel.class);
    b.childHandler(new nettyServerInitializer());

    // 服务器绑定端口监听
    ChannelFuture f = b.bind(portNumber).sync();
    // 监听服务器关闭监听
    f.channel().closeFuture().sync();

    // 可以简写为
    /* b.bind(portNumber).sync().channel().closeFuture().sync(); */
    } finally {
    bossGroup.shutdownGracefully();
    workerGroup.shutdownGracefully();
    }
    }
    }
  • nettyServerHandler

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.SimpleChannelInboundHandler;
    import io.netty.channel.socket.SocketChannel;
    import org.json.JSONObject;

    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    public class nettyServerHandler extends SimpleChannelInboundHandler<String> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
    // 收到消息直接打印输出
    // System.out.println(channelHandlerContext.channel().remoteAddress() + " Say : " + s);
    try {
    JSONObject jsonObject=new JSONObject(s+"}");
    // System.out.println(jsonObject.toString());
    }catch (Exception e){

    }
    String str="{\"id\":1233,\"type\":20,\"name\":\"name\",\"onoff\":1}";
    // 返回客户端消息 - 我已经接收到了你的消息
    // channelHandlerContext.writeAndFlush(str);
    }

    /*
    *
    * 覆盖 channelActive 方法 在channel被启用的时候触发 (在建立连接的时候)
    *
    * channelActive 和 channelInActive 在后面的内容中讲述,这里先不做详细的描述
    * */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
    String uuid = ctx.channel().id().asLongText();
    System.out.println(ctx.channel().remoteAddress());
    GatewayService.addGatewayChannel(ctx.channel().remoteAddress().toString(), (SocketChannel)ctx.channel());
    // System.out.println("RamoteAddress : " + ctx.channel().remoteAddress() + " active !");
    try {
    JSONObject jsonObject=new JSONObject(ctx.channel().remoteAddress()+"}");
    // System.out.println(jsonObject.toString());
    }catch (Exception e){

    }
    // String str="{\"id\":1233,\"type\":20,\"name\":\"name\",\"onoff\":0}";
    // ctx.writeAndFlush( "Welcome to " + InetAddress.getLocalHost().getHostName() + " service!\n");
    // ctx.writeAndFlush(str);

    super.channelActive(ctx);
    }
    // @Override
    // public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
    // }

    /**
    * 线程池
    */
    public void startThread(){
    ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    cachedThreadPool.execute(new Runnable() {
    public void run() {

    }
    });
    }
    }
  • nettyServerInitializer

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    import io.netty.buffer.ByteBuf;
    import io.netty.buffer.Unpooled;
    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.string.StringDecoder;
    import io.netty.handler.codec.string.StringEncoder;
    public class nettyServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
    ChannelPipeline pipeline = socketChannel.pipeline();

    ByteBuf delimiter = Unpooled.copiedBuffer("}".getBytes());
    // 以("\n")为结尾分割的 解码器Delimiters.lineDelimiter()
    pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, delimiter));

    // 字符串解码 和 编码
    pipeline.addLast("decoder", new StringDecoder());
    pipeline.addLast("encoder", new StringEncoder());

    // 自己的逻辑Handler
    pipeline.addLast("handler", new nettyServerHandler());
    }
    }
  • GatewayService
    用于其他地方控制socket
    如发送消息

    1
    GatewayService.getGatewayChannel("/192.168.1.250:23").writeAndFlush(str);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import io.netty.channel.socket.SocketChannel;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class GatewayService {
private static Map<String, SocketChannel> map = new ConcurrentHashMap<>();

public static void addGatewayChannel(String id, SocketChannel gateway_channel){
map.put(id, gateway_channel);
}

public static Map<String, SocketChannel> getChannels(){
return map;
}

public static SocketChannel getGatewayChannel(String id){
return map.get(id);
}

public static void removeGatewayChannel(String id){
map.remove(id);
}
}

客户端见:/2017/04/09/netty_client/