`

netty客户端发送消息

阅读更多
netty客户端与服务端通信

/**
* 先启动Server,再启动Client
* SimpleChannelInboundHandler
*/
public class NettyServer {
private int port=8088;

public static void main(String[] args) {
NettyServer server = new NettyServer();
server.run();
}

void run() {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(port))
.childHandler(new ChannelInitializer<SocketChannel>() {
public void initChannel(SocketChannel ch) {
//ch.pipeline().addLast("framer", new DelimiterBaseFrameDecoder(1024, Delimiters.lineDelimiter()));
//ch.pipeline().addLast(new SimpleSeverHandler());
ChannelPipeline p =ch.pipeline();
p.addLast("encoder", new SimpleEncoder());
p.addLast("handler", new SimpleSeverHandler());
}}
);
//.option(ChannelOption.SO_BACKLOG, 128)
//.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture f = b.bind(port).sync();
f.channel().closeFuture().sync();
}catch(Exception e) {
e.printStackTrace();
}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}

public class SimpleSeverHandler extends SimpleChannelInboundHandler {

protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf in = (ByteBuf)msg;
ByteBuffer byteBuffer = in.nioBuffer();
String res = decode(byteBuffer);
System.out.println(ctx.channel().remoteAddress()+" say: "+res);
ctx.writeAndFlush("receive your message!\n");
}

//解码 ByteBuf -> String
public static String decode(final ByteBuffer byteBuffer) {
        int length = byteBuffer.limit();
        byte[] data = new byte[length];
        byteBuffer.get(data);

        String s=null;
try {
s = new String(data, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
        return s;
    }

public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}

public class SimpleEncoder extends MessageToByteEncoder<String> {

    public void encode(ChannelHandlerContext ctx, String cmd, ByteBuf out)
        throws Exception {
        try {
            if (cmd != null) {
                out.writeBytes(cmd.getBytes());
            }
        } catch (Exception e) {
        e.printStackTrace();
        }
    }
}

客户端:
public class NettyClient {
private String host="127.0.0.1";
private int port = 8088;

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

public void run() {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.remoteAddress(new InetSocketAddress(host, port))
.handler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel ch)throws Exception {
ch.pipeline().addLast("handler",new ClientHandler2());
}
});
ChannelFuture f = b.connect().sync();
f.channel().closeFuture().sync();
}catch(Exception e) {
e.printStackTrace();
}
finally {
try {
group.shutdownGracefully().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public class ClientHandler2 extends SimpleChannelInboundHandler<ByteBuf>{
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf buf) throws Exception {
System.out.println("client channelRead0..");
System.out.println(buf.toString(Charset.forName("utf-8")));
}

public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("client channelActive..");
ctx.writeAndFlush(Unpooled.copiedBuffer("come from client?", CharsetUtil.UTF_8));
}

public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("client channelReadComplete..");
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}

public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("client exceptionCaught..");
cause.printStackTrace();
ctx.close();
}
}

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics