Telnet

来源:互联网 发布:jquery书籍推荐知乎 编辑:程序博客网 时间:2024/06/05 14:07

首先说明一下前提:

① 安装了Telnet客户端(服务器);② 本机防火墙开启了8080端口(入站规则);

后台使用的netty,会将Telnet发送的数据打印到控制台。

这里主要说明如何使用Telnet发送数据。

① cmd 进入dos

这里写图片描述


② 连接ip 端口

telnet localhost 8080

这里写图片描述


③ ctrl+]回显内容

这里写图片描述


④ 回车,进入编辑状态

这里写图片描述


⑤ 输入内容

这里写图片描述


后台支持

服务端:

package com.netty.discard;import io.netty.bootstrap.ServerBootstrap;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelOption;import io.netty.channel.EventLoopGroup;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioServerSocketChannel;/*** 丢弃任何进入的数据*/public class DiscardServer {    private int port;    public DiscardServer(int port) {        this.port = port;    }    public void run() throws Exception {        EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)        EventLoopGroup workerGroup = new NioEventLoopGroup();        ServerBootstrap b = new ServerBootstrap(); // (2)        try {            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class); // (3)            b.childHandler(new ChannelInitializer<SocketChannel>(){ // (4)                @Override                public void initChannel(SocketChannel ch) throws Exception {                    ch.pipeline().addLast(new DiscardServerHandler());                }            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true); // (6)            // 绑定端口,开始接收进来的连接            ChannelFuture f = b.bind(port).sync(); // (7)            // 等待服务器 socket 关闭 。            // 在这个例子中,这不会发生,但你可以优雅地关闭你的服务器。            f.channel().closeFuture().sync();        } finally {            workerGroup.shutdownGracefully();            bossGroup.shutdownGracefully();        }    }    public static void main(String[] args) throws Exception {        int port;        if (args.length > 0) {            port = Integer.parseInt(args[0]);        } else {            port = 8080;        }        new DiscardServer(port).run();    }}

处理器:

package com.netty.discard;import io.netty.buffer.ByteBuf;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.ChannelInboundHandlerAdapter;import io.netty.util.ReferenceCountUtil;/*** 处理服务端 channel.*/public class DiscardServerHandler extends ChannelInboundHandlerAdapter {     @Override    public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2)        // 默默地丢弃收到的数据//      ((ByteBuf) msg).release(); // (3)        ByteBuf in = (ByteBuf) msg;        try {            while(in.isReadable()){                System.out.print((char)in.readByte());                System.out.flush();            }        }finally{            ReferenceCountUtil.release(msg); // (2)        }     }    @Override    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)        // 当出现异常就关闭连接        cause.printStackTrace();        ctx.close();    }}
原创粉丝点击