基于netty框架提供socket服务端接口示例

先上代码,一睹为快!

import java.nio.charset.Charset;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class NettySocketServer {
	private int port = 9999;

	public void runServer() {
		NioEventLoopGroup boss = new NioEventLoopGroup();//接收线程
		NioEventLoopGroup worker = new NioEventLoopGroup();//工作线程
		try {
			ServerBootstrap server = new ServerBootstrap();
			server.group(boss, worker);//设置线程
			server.channel(NioServerSocketChannel.class);//设置服务类型   socket服务
			server.handler(new LoggingHandler(LogLevel.INFO));//设置日志处理器
			server.childHandler(new ChannelInitializer<SocketChannel>() {//增加初始化
				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					ChannelPipeline pipe = ch.pipeline();
					pipe.addLast(new StringEncoder(Charset.forName("UTF-8")));//出站编码处理
					pipe.addLast(new StringDecoder(Charset.forName("UTF-8")));//按照客户端的编码格式,将入参转为字符串,即下边的inbound handler里的msg为String类型
					pipe.addLast(new MyInServerHandler0());
				}
			});
			server.option(ChannelOption.SO_BACKLOG, 128);//官网示例
			server.childOption(ChannelOption.SO_KEEPALIVE, true);//官网示例
			//绑定端口并且添加监听和异步启动
			ChannelFuture future = server.bind(port).sync();//启动
			future.channel().closeFuture().sync();//启动
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			boss.shutdownGracefully();
			worker.shutdownGracefully();
		}
	}
	public class MyInServerHandler0 extends ChannelInboundHandlerAdapter {
		Log log = LogFactory.getLog(MyInServerHandler0.class);
		@Override
		public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
			String data = (String) msg;
			String ret = "我给你返回了";
			//返回值必须都得转成ByteBuf类型,或者在初始化的地方增加对应的出站编码器  比如StringEncoder
			//ctx.writeAndFlush(Unpooled.copiedBuffer(ret.getBytes("UTF-8")));
			log.info("MyInServerHandler0.channelRead");
			ctx.writeAndFlush(ret);
			ctx.close();
		}
		@Override
		public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
			log.info("MyInServerHandler0.exceptionCaught");
			ctx.writeAndFlush(cause.getMessage());
			ctx.close();
		}
	}
	public static void main(String[] args) {
		NettySocketServer serv = new NettySocketServer();
		serv.runServer();
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hard Bird

喜欢就赏一个吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值