java使用TCP协议传输报文,服务器端

首先是main方法

package org.fiberhome.action;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.fiberhome.service.ServerChannelInitializer;
import org.fiberhome.utils.TcpServiceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 服务器启动逻辑
 */
public class MainAction {


    public static void main(String[] args) throws Exception {
        int port = TcpServiceConfig.tcpPort;
        if (args != null && args.length > 0) {
            try {
                port = Integer.valueOf(args[0]);
            } catch (NumberFormatException e) {
                //采用默认值
            }
        }
        new MainAction().bind(port);
    }

    public void bind(int port) throws Exception {
        Logger log = LoggerFactory.getLogger(MainAction.class);
        //配置服务端的NIO线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, TcpServiceConfig.backlog)
                    .childHandler(new ServerChannelInitializer());

            //绑定端口,同步等待成功
            ChannelFuture f = b.bind(port).sync();
            log.info("服务已启动===========等待连接!!!");
            //等待服务器监听端口关闭;
            f.channel().closeFuture().sync();
        } finally {
            //优雅退出,释放线程池资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

 

服务器Channel通道初始化设置:
package org.fiberhome.service;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * 服务器Channel通道初始化设置
 */
public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        //字符串解码和编码
        pipeline.addLast("decoder", new StringDecoder());
        pipeline.addLast("encoder", new StringEncoder());
        //服务器的逻辑
        pipeline.addLast("handler", new TcpServerHandler());
    }
}
服务器业务逻辑:
package org.fiberhome.service;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.fiberhome.service.impl.TcpServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 服务器业务逻辑
 */

public class TcpServerHandler extends SimpleChannelInboundHandler {
    Logger log = LoggerFactory.getLogger(TcpServerHandler.class);
//    @Autowired
//    private TcpService tcpService;
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        String data= msg.toString();


//        System.out.println("Client say : " + msg.toString());
        //返回客户端消息 - 我已经接收到了你的消息
        ctx.writeAndFlush("Successful reception!");

        try {

            new TcpServiceImpl().insertWarning(data);

        }catch (Exception e){
            log.error("报文格式不合格!!!");

        }

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("RemoteAddress : " + ctx.channel().remoteAddress() + " active !");
        ctx.writeAndFlush("Successful connection!");
        super.channelActive(ctx);
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值