Netty: Socket: a demo

Netty: Socket: a demo


DTO

TransportObject.java

package com.me.dto;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class TransportObject implements Serializable {
   

    private String name;
    private int id;
    private List<String> list = new ArrayList<String>();

    public String getName() {
   
        return name;
    }

    public void setName(String name) {
   
        this.name = name;
    }

    public int getId() {
   
        return id;
    }

    public void setId(int id) {
   
        this.id = id;
    }

    public List<String> getList() {
   
        return list;
    }

    public void setList(List<String> list) {
   
        this.list = list;
    }

    @Override
    public String toString() {
   
        return "{" +
                "name='" + name + '\'' +
                ", id=" + id +
                ", list=" + list +
                '}';
    }

}


First Server

FirstClient.java

package com.me.socket.client;

import com.me.dto.TransportObject;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class FirstClient {
   

    private final String host;
    private final int port;

    public FirstClientHandler cl=new FirstClientHandler();

    public FirstClient() {
   
        this(0);
    }

    public FirstClient(int port) {
   
        this("localhost", port);
    }

    public FirstClient(String host, int port) {
   
        this.host = host;
        this.port = port;
    }

    public void connect(String msg) throws Exception {
   
        EventLoopGroup group = new NioEventLoopGroup();
        try {
   
            Bootstrap b = new Bootstrap();
            b.group(group) // 注册线程池
                    .channel(NioSocketChannel.class) // 使用NioSocketChannel来作为连接用的channel类
                    .remoteAddress(new InetSocketAddress(this.host, this.port)) // 绑定连接端口和host信息
                    .handler(new ChannelInitializer<SocketChannel>() {
    // 绑定连接初始化器
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
   
                            System.out.println("--------------------client: channel log begin--------------------");
                            System.out.println("正在连接中...");
                            ch.pipeline().addLast(new StringEncoder(Charset.forName("GBK")));
//                            ch.pipeline().addLast(new FirstClientHandler());
                            ch.pipeline().addLast(cl);
                            ch.pipeline().addLast(new ByteArrayEncoder());
                            ch.pipeline().addLast(new ChunkedWriteHandler());

                        }
                    });
            // System.out.println("服务端连接成功..");

            ChannelFuture cf = b.connect().sync(); // 异步连接服务器
            System.out.println("服务端连接成功..."); // 连接完成

//            channel = cf.channel();

            cl.myctx.writeAndFlush(Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8)); // 必须有flush

            cf.channel().closeFuture().sync(); // 异步等待关闭连接channel
            System.out.println("连接已关闭.."); // 关闭完成

        } finally {
   
            group.shutdownGracefully().sync(); // 释放线程池资源
        }
    }

    public static void main(String[] args) throws Exception {
   

        TransportObject data = new TransportObject();
        data.setId(999);
        data.setName("xyz");
        List<String> list = new ArrayList<String>();
        list.add("111");
        list.add("222");
        list.add("333");
        data.setList(list);

        // 8882: second-server, transfer data to second-server
        FirstClient firstClient = new FirstClient("127.0.0.1", 8882);
        firstClient.connect(data.toString());

        System.out.println("=========================");

    }
}

FirstClientHandler.java

package com.me.socket.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;

public class FirstClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
   

    public ChannelHandlerContext myctx;

    /**
     * 向服务端发送数据
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
   
        myctx=ctx;

        System.out.println("客户端与服务端通道-开启:" + ctx.channel().localAddress() + "channelActive");

//        String sendInfo = "Hello 这里是first客户端  你好啊!";
//        System.out.println("客户端准备发送的数据包:" + sendInfo);
//        ctx.writeAndFlush(Unpooled.copiedBuffer(sendInfo, CharsetUtil.UTF_8)); // 必须有flush

    }

    /**
     * channelInactive
     *
     * channel 通道 Inactive 不活跃的
     *
     * 当客户端主动断开服务端的链接后,这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据
     *
     */
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
   
        System.out.println("客户端与服务端通道-关闭:" + ctx.channel().localAddress() + "channelInactive");
        System.out.println("--------------------client: channel log end--------------------");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
   
        System.out.println("读取客户端通道信息..");
        ByteBuf buf = msg.readBytes(msg.readableBytes());
        System.out.println(
                "客户端接收到的服务端信息:" + ByteBufUtil.hexDump(buf) + "; 数据包为:" + buf.toString(Charset.forName("utf-8")));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
   
        ctx.close();
        System.out.println("异常退出:" + cause.getMessage());
    }
}

FirstServer.java

package com.me.socket.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值