Netty整合Socket客户端长链接

创建客户端连接
import com.alibaba.fastjson.JSONObject;
import com.lianfu.smartparking.controller.ThreadServerSocket;
import io.netty.bootstrap.Bootstrap;
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.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

public class Client implements Runnable {
final String HOST = System.getProperty(“host”, “192.168.0.173”);
final int PORT = Integer.parseInt(System.getProperty(“port”, “8087”));
final int SIZE = Integer.parseInt(System.getProperty(“size”, “1024”));
final Logger logger = LoggerFactory.getLogger(Client.class);

//@Async("taskExecutor")
public  void connect() throws InterruptedException {
    try {
      //  System.out.println("请求连接");
        logger.info("请求连接");
        sendMessage();
    }catch (Exception e){
        logger.error(e.getMessage());
    }

}
public  void sendMessage() throws InterruptedException {
    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast("decoder", new StringDecoder());
                        p.addLast("encoder", new StringEncoder());
                        p.addLast(new ClientHandler());
                    }
                });
        //JSONObject jsonObject=new JSONObject();
        //发送消息
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", "login");
        jsonObject.put("username","testID");
        jsonObject.put("password","123");
        ChannelFuture future = b.connect(HOST, PORT).sync();
        future.channel().writeAndFlush(jsonObject.toJSONString());
        //线程阻塞
      future.channel().closeFuture().sync();
        /*try {
            Thread.sleep(3000); // 主线程休眠3s保证程序不立即结束
        } catch (Exception e) {
                logger.error(e.getMessage());
        }*/
    } finally {
        group.shutdownGracefully();
    }
}

@Override
public void run() {
    try {
        this.connect();
    } catch (InterruptedException e) {
       // e.printStackTrace();
        logger.error(e.getMessage());
    }
}

}
关键代码
//线程阻塞
future.channel().closeFuture().sync();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值