Echo客户端和服务端

1.创建maven父模块以及子模块,
在这里插入图片描述
2.修改echoParent模块pom文件
在这里插入图片描述指定服务host以及端口号,引入exec插件
3.修改echoServer模块pom文件
在这里插入图片描述
拿到端口号,指定程序主入口
4.修改echoClient模块pom文件
在这里插入图片描述
EchoClient 模块代码:

public class EchoClient {

private	final String host;

private	final int port;

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

public void start() throws InterruptedException {
    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 socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new EchoClientHandler());
                    }
                });
        ChannelFuture f = b.connect().sync();
        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully().sync();
    }
}

public static void main(String[] args) throws InterruptedException {
    if(args.length !=2 ){
        System.out.println("usage:"+EchoServer.class.getSimpleName()+"<port>");
        return;
    }
    final String host = args[0];
    final int port = Integer.parseInt(args[1]);
    new EchoClient(host,port).start();
}

@Sharable
public class EchoClientHandler extends SimpleChannelInboundHandler {

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    ctx.writeAndFlush(Unpooled.copiedBuffer("Hello World!", CharsetUtil.UTF_8));
}

protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf in) throws Exception {
    System.out.println("client received:"+in.toString(CharsetUtil.UTF_8));
}

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

EchoServer模块代码:
public class EchoServer {

private final int port;

public EchoServer(int port) {
    this.port = port;
}

public static void main(String[] args) throws InterruptedException {
    if(args.length !=1 ){
        System.out.println("usage:"+EchoServer.class.getSimpleName()+"<port>");
        return;
    }
    //设置端口
    int port = Integer.parseInt(args[0]);
    //呼叫服务器,执行start方法
    new EchoServer(port).start();
}

public void start() throws InterruptedException {
    //创建EventLoopGroup
    NioEventLoopGroup group = new NioEventLoopGroup();
    try {
        //创建ServerBootstrap
        ServerBootstrap b = new ServerBootstrap();
        //指定使用NIO的传输channel(NioServerSocketChannel)为信道类型
        b.group(group).channel(NioServerSocketChannel.class).
                //设置socket的地址使用的端口
                localAddress(new InetSocketAddress(port))
                //添加EchoServerHandler到channel的channelpipeline
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch){
                        ch.pipeline().addLast(new EchoServerHandler());
                    }
                });

        //绑定的服务器,sync等待服务器关闭
        ChannelFuture f = b.bind().sync();
        //关闭channel,知道它被关闭
        System.out.println(EchoServer.class.getName()+"started and listen in"+f.channel().localAddress());
        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully().sync();
    }
}

@Sharable //标识类的实例之间可以在Channel里面共享
public class EchoServerHandler extends ChannelInboundHandlerAdapter {

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf in = (ByteBuf) msg;
    System.out.println("server received:"+in.toString(CharsetUtil.UTF_8));
    //将接收的消息返回给发送者,还没有冲刷消息
    ctx.write(in);
}

@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    //冲刷所有消息到远程节点,关闭通道后,操作完成
    ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    cause.printStackTrace();
    //关闭通道
    ctx.close();
}

接下来就是执行代码了!!!
在这里插入图片描述
5.进入echoParent目录下,执行mvn clean package打包,结果如下:
在这里插入图片描述
5.进入EchoServer目录下
在这里插入图片描述
执行echoServer模块Main函数,结果如下:
在这里插入图片描述
已经在开始监听99端口了。

6.进入Client模块目录,
在这里插入图片描述
在这里插入图片描述
结束。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值