IotSocketClient.java 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package com.persagy.socket;
  2. import java.net.InetSocketAddress;
  3. import io.netty.bootstrap.Bootstrap;
  4. import io.netty.channel.ChannelFuture;
  5. import io.netty.channel.ChannelInitializer;
  6. import io.netty.channel.EventLoopGroup;
  7. import io.netty.channel.nio.NioEventLoopGroup;
  8. import io.netty.channel.socket.SocketChannel;
  9. import io.netty.channel.socket.nio.NioSocketChannel;
  10. import io.netty.handler.codec.string.StringDecoder;
  11. import io.netty.handler.codec.string.StringEncoder;
  12. import io.netty.util.CharsetUtil;
  13. import lombok.extern.slf4j.Slf4j;
  14. /**
  15. *
  16. * @version 1.0.0
  17. * @company persagy
  18. * @author zhangqiankun
  19. * @date 2021年10月12日 上午10:06:34
  20. */
  21. @Slf4j
  22. public class IotSocketClient {
  23. public static final EventLoopGroup GROUP = new NioEventLoopGroup(1);
  24. public static final Bootstrap BS = new Bootstrap();
  25. static {
  26. // 注册线程池、使用NioSocketChannel来作为连接用的channel类
  27. BS.group(GROUP).channel(NioSocketChannel.class);
  28. }
  29. public static boolean connectAndSend(String host, int port, String command) {
  30. boolean result = false;
  31. ChannelFuture cf = null;
  32. try {
  33. BS.remoteAddress(new InetSocketAddress(host, port)) // 绑定连接端口和host信息
  34. .handler(new ChannelInitializer<SocketChannel>() { // 绑定连接初始化器
  35. @Override
  36. protected void initChannel(SocketChannel ch) throws Exception {
  37. log.info("正在连接中...");
  38. ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8));
  39. ch.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8));
  40. ch.pipeline().addLast(new IotClientHandler(command));
  41. }
  42. });
  43. cf = BS.connect().sync(); // 异步连接服务器
  44. log.info("服务端连接成功...");
  45. result = true;
  46. } catch (Exception e) {
  47. log.error("与服务端建立连接失败", e);
  48. } finally {
  49. if (cf != null) {
  50. try {
  51. cf.channel().closeFuture().sync();
  52. log.info("连接已关闭..");
  53. } catch (Exception e2) {
  54. log.error("未知异常", e2);
  55. }
  56. }
  57. }
  58. return result;
  59. }
  60. public static void main(String[] args) throws Exception {
  61. IotSocketClient.connectAndSend("192.168.100.102", 30054, "(5001120003;1;report;20220617100000;17107;ZD1060;1;902;155)");
  62. }
  63. }