java netty伺服器簡單例子
阿新 • • 發佈:2019-02-16
java netty 伺服器簡單例子
例子實現的功能是客戶端連線伺服器,伺服器返回當前時間的例子,使用maven匯入netty的包,其pom依賴為:
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.17.Final</version>
</dependency>
處理網路資料的程式如下:
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.io.UnsupportedEncodingException;
public class TimeServerHandler extends ChannelInboundHandlerAdapter {
//有連線可以讀取
@Override
public void channelRead(ChannelHandlerContext ctx,Object msg){
ByteBuf buf = (ByteBuf)msg;
byte [] req = new byte[buf.readableBytes()];
buf.readBytes(req);
try {
String body = new String(req,"UTF-8");
System.out.println("The time server receive order :" + body);
String currentTime = System.currentTimeMillis()+"";
ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
ctx.write(resp);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx){
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause){
System.out.println(cause.toString());
ctx.close();
}
}
伺服器初始化的程式如下:
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;
public class TimeServer {
public void bind(int port) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workGroup = new NioEventLoopGroup();
try{
ServerBootstrap b = new ServerBootstrap();
/*最大連線數量設定 BACKLOG用於構造服務端套接字ServerSocket物件,標識當伺服器請求處理執行緒全滿時,用於臨時存放已完成三次握手的請求的佇列的最大長度。如果未設定或所設定的值小於1,Java將使用預設值50。*/
b.group(bossGroup,workGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG,1024).childHandler(new ChildChannelHandler());
//繫結埠,等待同步成功
ChannelFuture f = b.bind(port).sync();
f.channel().closeFuture().sync();
}finally {
bossGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new TimeServerHandler());
}
}
public static void main(String[] args){
int port = 9000;
try {
new TimeServer().bind(port);
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用網路助手進行除錯,結果如下: