创建客户端连接
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();