日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

netty获取玩家chanel_Netty4.X 获取客户端IP

發布時間:2025/3/8 编程问答 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 netty获取玩家chanel_Netty4.X 获取客户端IP 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

最近使用netty-4.0.23.Final 版本編寫服務端代碼,有個獲取客戶端代碼的小需求,以前使用servlet開發時很機械的就:String?ipAddr="0.0.0.0";

if?(reqest.getHeader("X-Forwarded-For")?==?null)?{

ipAddr?=?reqest.getRemoteAddr();

}else{

ipAddr?=?req.getHeader("X-Forwarded-For");

}

ps:X-Forwarded-For 是使用了代理(如nginx)會附加在HTTP頭域上的。

理解好HTTP協議基礎知識很重要這里不陳述。

Netty提供異步的、事件驅動的網絡應用程序框架和工具,用以快速開發高性能、高可靠性的網絡服務器和客戶端程序,支持多種協議,當然也支持HTTP協議。

啟動Netty服務的程序:public?void?start()?throws?Exception?{

EventLoopGroup?bossGroup?=?new?NioEventLoopGroup(1);

EventLoopGroup?workerGroup?=?new?NioEventLoopGroup();

try?{

ServerBootstrap?bootstrap?=?new?ServerBootstrap();

bootstrap.option(ChannelOption.SO_BACKLOG,?1024);

bootstrap.group(bossGroup,?workerGroup)

.channel(NioServerSocketChannel.class)

.handler(new?LoggingHandler(LogLevel.INFO))

.childHandler(new?ServerHandlerInitializer());

Channel?ch?=?bootstrap.bind(8080).sync().channel();

System.err.println("Open?your?web?browser?and?navigate?to?"

+?("http")?+?"://127.0.0.1:8080/");

ch.closeFuture().sync();

}?catch?(Exception?e)?{

e.printStackTrace();

}?finally?{

bossGroup.shutdownGracefully();

workerGroup.shutdownGracefully();

}

}

public?class?ServerHandlerInitializer?extends?ChannelInitializer?{

@Override

protected?void?initChannel(SocketChannel?channel)?throws?Exception?{

ChannelPipeline?p?=?channel.pipeline();

p.addLast(new?HttpRequestDecoder());

p.addLast(new?HttpResponseEncoder());

p.addLast(new?ServerHandler());

}

}

看出NioServerSocketChannel類的源碼可以知道是對java.nio.channels.ServerSocketChannel重新封裝,所以在獲取客戶端IP時調用remoteAddress()強轉成java.net.InetSocketAddress即可獲取。public?class?ServerHandler?extends?SimpleChannelInboundHandler?{

@Override

public?void?channelRead0(ChannelHandlerContext?ctx,?HttpObject?msg)

throws?Exception?{

if?(msg?instanceof?HttpRequest)?{

HttpRequest?mReq?=?(HttpRequest)?msg;

String?clientIP?=?mReq.headers().get("X-Forwarded-For");

if?(clientIP?==?null)?{

InetSocketAddress?insocket?=?(InetSocketAddress)?ctx.channel()

.remoteAddress();

clientIP?=?insocket.getAddress().getHostAddress();

}

}

}

}

這樣我們就可以獲取到客戶端的IP了。

總結

以上是生活随笔為你收集整理的netty获取玩家chanel_Netty4.X 获取客户端IP的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。