|
|
@@ -0,0 +1,63 @@
|
|
|
+package cn.vbdsm.hj212.modbus.server;
|
|
|
+
|
|
|
+import cn.vbdsm.hj212.modbus.handler.TcpClientHandler;
|
|
|
+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 lombok.Getter;
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.springframework.beans.factory.annotation.Value;
|
|
|
+import org.springframework.stereotype.Component;
|
|
|
+
|
|
|
+import java.net.InetSocketAddress;
|
|
|
+import java.util.Scanner;
|
|
|
+
|
|
|
+@Component
|
|
|
+@Slf4j
|
|
|
+public class TcpSocketClient {
|
|
|
+
|
|
|
+ @Getter
|
|
|
+ private Bootstrap bootstrap;
|
|
|
+ @Getter
|
|
|
+ private Channel channel;
|
|
|
+
|
|
|
+ @Value("${vbdsm.socket.client.port}")
|
|
|
+ private int port;
|
|
|
+ @Value("${vbdsm.socket.client.bindIp}")
|
|
|
+ private String host;
|
|
|
+
|
|
|
+ public void connect(){
|
|
|
+ EventLoopGroup group = new NioEventLoopGroup();
|
|
|
+ this.bootstrap = new Bootstrap();
|
|
|
+ bootstrap.group(group).channel(NioSocketChannel.class)
|
|
|
+ .option(ChannelOption.TCP_NODELAY, true)
|
|
|
+ .handler(new ChannelInitializer<SocketChannel>() {
|
|
|
+ @Override
|
|
|
+ protected void initChannel(SocketChannel ch) throws Exception {
|
|
|
+// ch.pipeline().addLast("decoder",new DealMsg()); //设置自定义解码器
|
|
|
+// ch.pipeline().addLast("encoder",new MsgEncode()); //设置自定义编码器
|
|
|
+ ch.pipeline().addLast(new TcpClientHandler());//设置客户端网络IO处理器
|
|
|
+ }
|
|
|
+ });
|
|
|
+ //连接服务器 同步等待成功
|
|
|
+ ChannelFuture f = bootstrap.connect(new InetSocketAddress(host, port));
|
|
|
+ //同步等待客户端通道关闭
|
|
|
+ try {
|
|
|
+ this.channel = f.sync().channel();
|
|
|
+ } catch (InterruptedException e) {
|
|
|
+ throw new RuntimeException(e);
|
|
|
+ }
|
|
|
+ //释放线程组资源
|
|
|
+ //group.shutdownGracefully();
|
|
|
+ }
|
|
|
+
|
|
|
+ public void sendMsg(String msg){
|
|
|
+ try {
|
|
|
+ this.channel.writeAndFlush(msg);
|
|
|
+ } catch (Exception e) {
|
|
|
+ throw new RuntimeException(e);
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|