《一步一步實現神卓內網穿透功能,netty通信基礎》之客戶端發送信息給服務器,一直等待服務器的迴應,服務器收到迴應後返回信息給服務端,客戶端收到迴應,等待結束,核心重點是CountDownLatch類的使用。
CountDownLatch能夠使一個或多個線程等待其他線程完成各自的工作後再執行;CountDownLatch是JDK 5+裏面閉鎖的一個實現。
方法如下:
public CountDownLatch(int count); //指定計數的次數,只能被設置1次
public void countDown(); //調用此方法則計數減1
public void await() throws InterruptedException //調用此方法會一直阻塞當前線程,直到計時器的值爲0,除非線程被中斷。
Public Long getCount(); //得到當前的計數
Public boolean await(long timeout, TimeUnit unit) //調用此方法會一直阻塞當前線程,直到計時器的值爲0,除非線程被中斷或者計數器超時,返回false代表計數器超時。
From Object Inherited:
Clone、equals、hashCode、notify、notifyALL、wait等。
該類使用的一個參考例子:
public class CountDownLatchDemo {
final static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch=new CountDownLatch(2);//兩個工人的協作
Worker worker1=new Worker("zhang san", 5000, latch);
Worker worker2=new Worker("li si", 8000, latch);
worker1.start();//
worker2.start();//
latch.await();//等待所有工人完成工作
System.out.println("all work done at "+sdf.format(new Date()));
}
static class Worker extends Thread{
String workerName;
int workTime;
CountDownLatch latch;
public Worker(String workerName ,int workTime ,CountDownLatch latch){
this.workerName=workerName;
this.workTime=workTime;
this.latch=latch;
}
public void run(){
System.out.println("Worker "+workerName+" do work begin at "+sdf.format(new Date()));
doWork();//工作了
System.out.println("Worker "+workerName+" do work complete at "+sdf.format(new Date()));
latch.countDown();//工人完成工作,計數器減一
}
private void doWork(){
try {
Thread.sleep(workTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
接下來是本文重點,netty客戶端(直接粘貼複製就可運行)
EchoClient.java
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.concurrent.CountDownLatch;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;
public class EchoClient {
private final String host;
private final int port;
public EchoClient() {
this(0);
}
public EchoClient(int port) {
this("localhost", port);
}
public EchoClient(String host, int port) {
this.host = host;
this.port = port;
}
public String start() throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
String result="";
CountDownLatch lathc = new CountDownLatch(1);
EchoClientHandler handle=new EchoClientHandler(lathc);
try {
Bootstrap b = new Bootstrap();
b.group(group) // 註冊線程池
.channel(NioSocketChannel.class) // 使用NioSocketChannel來作爲連接用的channel類
.remoteAddress(new InetSocketAddress(this.host, this.port)) // 綁定連接端口和host信息
.handler(new ChannelInitializer<SocketChannel>() { // 綁定連接初始化器
@Override
protected void initChannel(SocketChannel ch) throws Exception {
System.out.println("正在連接中...");
ch.pipeline().addLast(new StringEncoder(Charset.forName("GBK")));
ch.pipeline().addLast(handle);
ch.pipeline().addLast(new ByteArrayEncoder());
ch.pipeline().addLast(new ChunkedWriteHandler());
}
});
// System.out.println("服務端連接成功..");
ChannelFuture cf = b.connect().sync(); // 異步連接服務器
System.out.println("服務端連接成功..."); // 連接完成
lathc.await();//開啓等待會等待服務器返回結果之後再執行下面的代碼
System.out.println("服務器返回 1:" + handle.getResult());
result= handle.getResult();
cf.channel().closeFuture().sync(); // 異步等待關閉連接channel
System.out.println("連接已關閉.."); // 關閉完成
} finally {
group.shutdownGracefully().sync(); // 釋放線程池資源
}
return result;
}
public static void main(String[] args) throws Exception {
EchoClient clientrequest=new EchoClient("127.0.0.1", 8888);
clientrequest.start();
}
EchoClientHandler.java
import java.nio.charset.Charset;
import java.util.concurrent.CountDownLatch;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
private CountDownLatch lathc;
private String result;//服務端返回的結果
public EchoClientHandler(CountDownLatch lathc){
this.lathc=lathc;
}
/**
* 向服務端發送數據
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("客戶端與服務端通道-開啓:" + ctx.channel().localAddress() + "channelActive");
String sendInfo = "Hello 這裏是客戶端 你好啊!";
System.out.println("客戶端準備發送的數據包:" + sendInfo);
ctx.writeAndFlush(Unpooled.copiedBuffer(sendInfo, CharsetUtil.UTF_8)); // 必須有flush
}
/**
* channelInactive
*
* channel 通道 Inactive 不活躍的
*
* 當客戶端主動斷開服務端的鏈接後,這個通道就是不活躍的。也就是說客戶端與服務端的關閉了通信通道並且不可以傳輸數據
*
*/
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("客戶端與服務端通道-關閉:" + ctx.channel().localAddress() + "channelInactive");
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
System.out.println("讀取客戶端通道信息..");
ByteBuf buf = msg.readBytes(msg.readableBytes());
System.out.println(
"客戶端接收到的服務端信息:" + ByteBufUtil.hexDump(buf) + "; 數據包爲:" + buf.toString(Charset.forName("utf-8")));
result=buf.toString(Charset.forName("utf-8"));
lathc.countDown();//消息收取完畢後釋放同步鎖 計數器減去1
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
System.out.println("異常退出:" + cause.getMessage());
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
接下來是服務端的代碼(直接粘貼複製就可運行)
EchoServer.java
import java.nio.charset.Charset;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.codec.string.StringEncoder;
public class EchoServer {
private final int port;
public EchoServer(int port) {
this.port = port;
}
public void start() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup group = new NioEventLoopGroup();
try {
ServerBootstrap sb = new ServerBootstrap();
sb.option(ChannelOption.SO_BACKLOG, 1024);
sb.group(group, bossGroup) // 綁定線程池
.channel(NioServerSocketChannel.class) // 指定使用的channel
.localAddress(this.port)// 綁定監聽端口
.childHandler(new ChannelInitializer<SocketChannel>() { // 綁定客戶端連接時候觸發操作
@Override
protected void initChannel(SocketChannel ch) throws Exception {
System.out.println("報告");
System.out.println("信息:有一客戶端鏈接到本服務端");
System.out.println("IP:" + ch.localAddress().getHostName());
System.out.println("Port:" + ch.localAddress().getPort());
System.out.println("報告完畢");
ch.pipeline().addLast(new StringEncoder(Charset.forName("GBK")));
ch.pipeline().addLast(new EchoServerHandler()); // 客戶端觸發操作
ch.pipeline().addLast(new ByteArrayEncoder());
}
});
ChannelFuture cf = sb.bind().sync(); // 服務器異步創建綁定
System.out.println(EchoServer.class + " 啓動正在監聽: " + cf.channel().localAddress());
cf.channel().closeFuture().sync(); // 關閉服務器通道
} finally {
group.shutdownGracefully().sync(); // 釋放線程池資源
bossGroup.shutdownGracefully().sync();
}
}
public static void main(String[] args) throws Exception {
new EchoServer(8888).start(); // 啓動
}
}
EchoServerHandler.java
import java.io.UnsupportedEncodingException;
import java.util.Date;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
/*
* channelAction
*
* channel 通道 action 活躍的
*
* 當客戶端主動鏈接服務端的鏈接後,這個通道就是活躍的了。也就是客戶端與服務端建立了通信通道並且可以傳輸數據
*
*/
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println(ctx.channel().localAddress().toString() + " 通道已激活!");
}
/*
* channelInactive
*
* channel 通道 Inactive 不活躍的
*
* 當客戶端主動斷開服務端的鏈接後,這個通道就是不活躍的。也就是說客戶端與服務端的關閉了通信通道並且不可以傳輸數據
*
*/
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println(ctx.channel().localAddress().toString() + " 通道不活躍!");
// 關閉流
}
/**
*
* @author Taowd
* TODO 此處用來處理收到的數據中含有中文的時 出現亂碼的問題
* 2017年8月31日 下午7:57:28
* @param buf
* @return
*/
private String getMessage(ByteBuf buf) {
byte[] con = new byte[buf.readableBytes()];
buf.readBytes(con);
try {
return new String(con, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
/**
* 功能:讀取服務器發送過來的信息
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// 第一種:接收字符串時的處理
ByteBuf buf = (ByteBuf) msg;
String rev = getMessage(buf);
System.out.println("客戶端收到服務器數據:" + rev);
String reply="我已經收到信息:時間爲"+new Date();
ByteBuf resp=Unpooled.copiedBuffer(reply.getBytes());
ctx.write(resp);
}
/**
* 功能:讀取完畢客戶端發送過來的數據之後的操作
*/
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("服務端接收數據完畢..");
// 第一種方法:寫一個空的buf,並刷新寫出區域。完成後關閉sock channel連接。
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
// ctx.flush();
// ctx.flush(); //
// 第二種方法:在client端關閉channel連接,這樣的話,會觸發兩次channelReadComplete方法。
// ctx.flush().close().sync(); // 第三種:改成這種寫法也可以,但是這中寫法,沒有第一種方法的好。
}
/**
* 功能:服務端發生異常的操作
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
System.out.println("異常信息:\r\n" + cause.getMessage());
}
}
要導入的包:
相信一看就懂。有問題歡迎留言!