netty的tcp服务端

jar包下载,http://pan.baidu.com/s/1hr2VBzY
import org.apache.log4j.Logger;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
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 NettyServerBootstrap {


private static Logger logger = Logger.getLogger(NettyServerBootstrap.class);


private int port;


public NettyServerBootstrap(int port) {
this.port = port;
bind();
}


private void bind() {


EventLoopGroup boss = new NioEventLoopGroup();
EventLoopGroup worker = new NioEventLoopGroup();


try {


ServerBootstrap bootstrap = new ServerBootstrap();


bootstrap.group(boss, worker);
bootstrap.channel(NioServerSocketChannel.class);
bootstrap.option(ChannelOption.SO_BACKLOG, 1024); //连接数
bootstrap.option(ChannelOption.TCP_NODELAY, true);  //不延迟,消息立即发送
bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); //长连接
bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel)
throws Exception {
ChannelPipeline p = socketChannel.pipeline();
p.addLast(new NettyServerHandler());
}
});
ChannelFuture f = bootstrap.bind(port).sync();
if (f.isSuccess()) {
logger.debug("启动Netty服务成功,端口号:" + this.port);
System.out.println("启动Netty服务成功,端口号:" + this.port);
}
// 关闭连接
f.channel().closeFuture().sync();


} catch (Exception e) {
logger.error("启动Netty服务异常,异常信息:" + e.getMessage());
System.out.println("启动Netty服务异常,异常信息:" + e.getMessage());
e.printStackTrace();
} finally {
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}


public static void main(String[] args) throws InterruptedException {

NettyServerBootstrap server= new NettyServerBootstrap(9999);


}


}


//具体实现



import java.io.UnsupportedEncodingException;


import com.sun.xml.internal.fastinfoset.stax.events.Util;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;


public class NettyServerHandler extends ChannelHandlerAdapter {


@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {

ByteBuf buf = (ByteBuf) msg;

String recieved = getMessage(buf);
System.out.println("服务器接收到消息:" + recieved);
int i=0;
if(!Util.isEmptyString(recieved)&&i<2){
try {
ctx.writeAndFlush(getSendByteBuf("APPLE"));
i++;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/*try {
ctx.writeAndFlush(getSendByteBuf("APPLE"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}*/
}


/*
* 从ByteBuf中获取信息 使用UTF-8编码返回
*/
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;
}
}

private ByteBuf getSendByteBuf(String message)
throws UnsupportedEncodingException {


byte[] req = message.getBytes("UTF-8");
ByteBuf pingMessage = Unpooled.buffer();
pingMessage.writeBytes(req);


return pingMessage;
}
}

netty先启动服务端,然后在启动客户端进行数据交互,这里啰嗦一下

Netty是一个高性能、异步事件驱动的网络应用框架,特别适合用于构建高并发的HTTP服务器。它提供了一套完整的事件循环机制和丰富的API,使得开发者能够轻松地处理HTTP请求和响应。 在Netty中创建HTTP服务端的主要步骤包括: 1. **初始化ServerBootstrap**:创建一个`ServerBootstrap`实例,这是启动服务器的核心工具,配置相关的处理器工厂如ChannelInitializer。 2. **配置HttpServerCodec**:选择一个合适的`HttpServerCodec`,负责HTTP协议解析和编码,将TCP数据包转化为HTTP请求和响应。 3. **设置Handler**:创建一个实现了`ChannelInboundHandler`接口的类,例如`HttpObjectAggregator`用于聚合HTTP消息,`HttpRequestHandler`处理实际的业务逻辑。 4. **绑定端口**:通过`bootstrap.bind()`方法指定服务器监听的地址和端口,并开始接受连接。 5. **注册管道组件**:将自定义的ChannelInitializer添加到`bootstrap.group()`,这个初始化器会按照配置顺序组装通道组件。 示例代码片段大致如下: ```java EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { // 初始化处理器链路 ch.pipeline().addLast( new HttpServerCodec(), new HttpObjectAggregator(65536), new HttpRequestHandler() ); } }); ChannelFuture f = b.bind(port).sync(); f.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值