netty4.0使用
来源:互联网 发布:网络上最近挺火的歌曲 编辑:程序博客网 时间:2024/05/16 02:02
创建server端:
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.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
public class ConstractorServerNetty {
private void constractServerNetty() {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap sbs = new ServerBootstrap();
sbs.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.localAddress(10000)
.childOption(ChannelOption.TCP_NODELAY,true)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
public void initChannel(NioSocketChannel ch) throws Exception {
ch.pipeline().addLast(new EchoServerHandler());
}
});
ChannelFuture f = sbs.bind().sync();
f.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new ConstractorServerNetty().constractServerNetty();
}
}
server的handler:
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundByteHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.***.mytest.utils.NumberUtil;
public class EchoServerHandler extends ChannelInboundByteHandlerAdapter {
private final Logger logger = LoggerFactory.getLogger(EchoServerHandler.class);
@Override
protected void inboundBufferUpdated(ChannelHandlerContext ctx, ByteBuf bytebuf)
throws Exception {
boolean flag = ctx.hasInboundByteBuffer();
if(flag) {
//返回个副本,原bytebuf可读的字节
//bytebuf = bytebuf.copy();
//缓冲区实际可读字节数量
int size = bytebuf.readableBytes();
logger.debug("========bytebuf total size ["+size+"]");
int headerSize =0;
if(size>4) {
byte[] sizeByte = new byte[4];
bytebuf.readBytes(sizeByte);
headerSize = NumberUtil.byteArrayToInt(sizeByte);
logger.debug("=======header size ["+headerSize+"]");
}
if(headerSize==0) {
logger.debug("====headerSize is not enough=====");
return;
}
byte[] received = new byte[headerSize];
//将信息从bytebuf读入到result中
bytebuf.readBytes(received);
logger.debug("==================="+new String(received,"utf-8"));
ByteBuf out = ctx.nextOutboundByteBuffer();
String returnInfo = "It's ok!";
returnInfo+="\n"; //加上\n 以便inputStream转换bufferedReader读取数据
out.writeBytes(returnInfo.getBytes("utf-8"));
ctx.flush();
}else {
logger.debug("========inboundByteBuffer has not info===========");
}
}
}
客户端:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import com.***.mytest.utils.NumberUtil;
public class Client {
public static void main(String[] args) throws IOException {
PrintWriter pw = null;
OutputStream out = null;
InputStream in = null;
try {
Socket socket = new Socket();
socket.connect(new InetSocketAddress("127.0.0.1",10000));
out = socket.getOutputStream();
String s = "abcccc";
int longer = s.length();
byte[] size = NumberUtil.intToByteArray(longer);
pw = new PrintWriter(out);
pw.write(new String(size,"utf-8"));
pw.write(s);
pw.flush();
out.flush();
in = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
System.out.println(reader.readLine()+" client received info ");
} catch (Exception e) {
e.printStackTrace();
}finally {
if(pw!=null) {
pw.close();
}
if(out!=null) {
out.close();
}
if(in!=null) {
in.close();
}
}
}
}
4字节数组与int相互转化,网络传输中很多用前4个字节代表数据内容的长度。
public static byte[] intToByteArray(int num) {
byte[] bytes = new byte[4];
bytes[0] = (byte) (num >> 24);
bytes[1] = (byte) (num >> 16);
bytes[2] = (byte) (num >> 8);
bytes[3] = (byte) (num);
return bytes;
}
public static int byteToInt(byte[] bytes){
return Integer.valueOf(""+ (((bytes[0] & 0x000000ff) << 24) | ((bytes[1] & 0x000000ff) << 16)
| ((bytes[2] & 0x000000ff) << 8) | (bytes[3] & 0x000000ff)));
}
}
- netty4.0使用
- Netty4.0中LengthFieldBasedFrameDecoder的使用心得
- Netty4 使用总结
- Netty4.0.36使用入门
- netty4初步使用
- netty4 UDP的使用
- netty4.x FixedChannelPool使用
- Netty4.0 用户指南
- Netty4.0 用户指南
- Netty4.0学习笔记
- Netty4.0 用户指南
- 使用Spring+Maven配置Netty4
- Netty4框架的初步使用
- Netty4.0 开发指导 2
- Netty4.0 开发指导 1
- Netty4.0 简单服务器应用
- Netty4.0学习笔记系列之四:混合使用coder和handler
- Netty4.0学习笔记系列之四:混合使用coder和handler
- select函数分析
- java内存回收机制GC
- IOS开发之----XCode4.5如何找到以前的iphone模拟器和IOS开发文档
- jode反编译插件出现的问题以及解决方法
- Ubuntu 下vivi的移植
- netty4.0使用
- (转)Kinect+OpenNI学习笔记
- CareerCup-1.3
- 欢迎您在新浪博客安家
- Dreamweaver中如何设定文字——大小、字体、颜色
- 腾讯2011.10.15校园招聘会笔…
- 2011年11月12日
- 2011年11月13日
- 接触linux有感