Netty整合socket實現接受傳送訊息
阿新 • • 發佈:2019-01-10
注意及日誌輸出很詳細了
故不再講解:
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.haiyang.key.Model.Socket.*; import com.haiyang.key.Service.VersionService; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.text.SimpleDateFormat; import java.util.Date; //自定義的ChannelHandler @Component public class HelloServerHandler extends ChannelHandlerAdapter { @Autowired private VersionService versionService; private static VersionService v; private static Logger logger = Logger.getLogger(HelloServerHandler.class); @PostConstruct public void init(){ v = this.versionService; logger.info(v); logger.info("-----------------"); logger.info(this.versionService); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { logger.info("客戶端連線上了"); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf=(ByteBuf) msg; byte[] req=new byte[buf.readableBytes()]; buf.readBytes(req); String body=new String(req,"UTF-8"); logger.info("伺服器端接收的訊息:"+body); try{ //這個analysis是處理部分 返回String型別 String dispose = analysis(body); logger.info("伺服器返回的訊息:"+dispose); ByteBuf resp= Unpooled.copiedBuffer(dispose.getBytes()); //返回給客戶端 ctx.write(resp); }catch (Exception e){ Errorr errorr = new Errorr(); errorr.setType("500"); try{ //擷取異常 errorr.setResult(e.toString().split(":")[1]); }catch (Exception e2){ errorr.setResult("請聯絡管理員處理!"); } String dispose = JSON.toJSONString(errorr); logger.info("伺服器返回的訊息:"+dispose); ByteBuf resp= Unpooled.copiedBuffer(dispose.getBytes()); ctx.write(resp); } } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 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; import org.springframework.stereotype.Component; /** * Socket程式設計服務端 */ @Component public class HelloServer { public void bind() throws InterruptedException { EventLoopGroup bossGruop=new NioEventLoopGroup();//用於伺服器端接受客戶端的連線 EventLoopGroup workGroup=new NioEventLoopGroup();//用於網路事件的處理 try { ServerBootstrap b=new ServerBootstrap(); b.group(bossGruop, workGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel arg0) throws Exception { arg0.pipeline().addLast(new HelloServerHandler()); } }).option(ChannelOption.SO_BACKLOG, 9999);//指定此套介面排隊的最大連線個數 ChannelFuture f=b.bind(18869).sync(); //監聽埠號 f.channel().closeFuture().sync(); } finally { bossGruop.shutdownGracefully(); workGroup.shutdownGracefully(); } } }
有什麼不懂的還可以看這位大佬:
https://www.cnblogs.com/xujian2014/p/5704316.html
寫的很不錯,靜下心來慢慢看。