看了好幾天的netty實戰,慢慢摸索,雖然尚未摸着不少門道,但今天仍是把以前想加入到項目裏的html
一些想法實現了,算是有點信心了吧(講真netty對初學者還真的不是很友好......)java
首先,固然是在SpringBoot項目裏添加netty的依賴了,注意不要用netty5的依賴,由於已經廢棄了spring
<!--netty--> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.32.Final</version> </dependency>
將端口和IP寫入application.yml文件裏,我這裏是我雲服務器的內網IP,若是是本機測試,用127.0.0.1就ok數據庫
netty: port: 7000 url: 172.16.0.7
在這以後,開始寫netty的服務器,這裏服務端的邏輯就是將客戶端發來的信息返回回去apache
由於採用依賴注入的方法實例化netty,因此加上@Component註解bootstrap
1 package com.safelocate.app.nettyServer; 2 3 import io.netty.bootstrap.ServerBootstrap; 4 import io.netty.channel.*; 5 import io.netty.channel.nio.NioEventLoopGroup; 6 import io.netty.channel.socket.nio.NioServerSocketChannel; 7 import org.apache.log4j.Logger; 8 import org.springframework.stereotype.Component; 9 10 import java.net.InetSocketAddress; 11 12 @Component 13 public class NettyServer { 14 //logger 15 private static final Logger logger = Logger.getLogger(NettyServer.class); 16 public void start(InetSocketAddress address){ 17 EventLoopGroup bossGroup = new NioEventLoopGroup(1); 18 EventLoopGroup workerGroup = new NioEventLoopGroup(); 19 try { 20 ServerBootstrap bootstrap = new ServerBootstrap() 21 .group(bossGroup,workerGroup) 22 .channel(NioServerSocketChannel.class) 23 .localAddress(address) 24 .childHandler(new ServerChannelInitializer()) 25 .option(ChannelOption.SO_BACKLOG, 128) 26 .childOption(ChannelOption.SO_KEEPALIVE, true); 27 // 綁定端口,開始接收進來的鏈接 28 ChannelFuture future = bootstrap.bind(address).sync(); 29 logger.info("Server start listen at " + address.getPort()); 30 future.channel().closeFuture().sync(); 31 } catch (Exception e) { 32 e.printStackTrace(); 33 bossGroup.shutdownGracefully(); 34 workerGroup.shutdownGracefully(); 35 } 36 } 37 38 }
固然,這裏的ServerChannelInitializer是我本身定義的類,這個類是繼承ChannelInitializer<SocketChannel>的,裏面設置出站和入站的編碼器和解碼器數組
package com.safelocate.app.nettyServer; import io.netty.channel.ChannelInitializer; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.util.CharsetUtil; public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel channel) throws Exception { channel.pipeline().addLast("decoder",new StringDecoder(CharsetUtil.UTF_8)); channel.pipeline().addLast("encoder",new StringEncoder(CharsetUtil.UTF_8)); channel.pipeline().addLast(new ServerHandler()); } }
最好注意被別decoder和encoder寫成了同樣的,否則會出問題(我以前就是不當心都寫成了StringDecoder...)緩存
在這以後就是設置ServerHandler來處理一些簡單的邏輯了安全
package com.safelocate.app.nettyServer; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.SimpleChannelInboundHandler; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; public class ServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) { System.out.println("channelActive----->"); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println("server channelRead......"); System.out.println(ctx.channel().remoteAddress()+"----->Server :"+ msg.toString()); //將客戶端的信息直接返回寫入ctx ctx.write("server say :"+msg); //刷新緩存區 ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } }
準備工做到這裏,如今要作到就是去啓動這個程序服務器
將AppApplication實現CommandLineRunner這個接口,這個接口能夠用來再啓動SpringBoot時同時啓動其餘功能,好比配置,數據庫鏈接等等
而後重寫run方法,在run方法裏啓動netty服務器,Server類用@AutoWired直接實例化
package com.safelocate.app; import com.safelocate.app.nettyServer.NettyServer; import io.netty.channel.ChannelFuture; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import java.net.InetAddress; import java.net.InetSocketAddress; @SpringBootApplication public class AppApplication implements CommandLineRunner { @Value("${netty.port}") private int port; @Value("${netty.url}") private String url; @Autowired private NettyServer server; public static void main(String[] args) { SpringApplication.run(AppApplication.class, args); } @Override public void run(String... args) throws Exception { InetSocketAddress address = new InetSocketAddress(url,port); System.out.println("run .... . ... "+url); server.start(address); } }
ok,到這裏服務端已經寫完,本地我也已經測試完,如今須要打包部署服務器,固然這個程序只爲練手...
控制檯輸入mvn clean package -D skipTests 而後將jar包上傳服務器,在這以後,須要在騰訊雲/阿里雲那邊配置好安全組,將以前yml文件裏設定的端口的入站
規則設置好,否則訪問會被拒絕
以後java -jar命令運行,若是需保持後臺一直運行 就用nohup命令,能夠看到程序已經跑起來了,等待客戶端鏈接交互
以後就是寫客戶端了,客戶端實際上是依葫蘆畫瓢,跟上面相似
Handler
package client; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; public class ClientHandler extends ChannelInboundHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) { System.out.println("ClientHandler Active"); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { System.out.println("--------"); System.out.println("ClientHandler read Message:"+msg); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } }
ChannelInitializer
package client; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.util.CharsetUtil; public class ClientChannelInitializer extends ChannelInitializer<SocketChannel> { protected void initChannel(SocketChannel channel) throws Exception { ChannelPipeline p = channel.pipeline(); p.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8)); p.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8)); p.addLast(new ClientHandler()); } }
主函數所在類,即客戶端
package client; import io.netty.bootstrap.Bootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; public class Client { static final String HOST = System.getProperty("host", "服務器的IP地址"); static final int PORT = Integer.parseInt(System.getProperty("port", "7000")); static final int SIZE = Integer.parseInt(System.getProperty("size", "256")); public static void main(String[] args) throws Exception { sendMessage("hhhh"); } public static void sendMessage(String content) throws InterruptedException{ // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast("decoder", new StringDecoder()); p.addLast("encoder", new StringEncoder()); p.addLast(new ClientHandler()); } }); ChannelFuture future = b.connect(HOST, PORT).sync(); future.channel().writeAndFlush(content); future.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } } }
啓動客戶端,這裏就是簡單發送一條"hhhh",能夠看到客戶端已經收到服務器發來的信息
而後再看服務端,也有相應的信息打印
推薦一個挺好的學netty的博客,https://blog.csdn.net/linuu/article/details/51306480,搭配netty實戰這本書一塊兒學習效果很好
實戰:根據上面完成一個簡(la)單(ji)的聊天室應用(無界面,基於CMD)
這裏服務端能夠單獨分出來能夠單獨做爲一個工程打包爲jar,萬萬不必Springboot,但這裏懶得改了,就仍是當後臺用吧hhh
首先,服務端須要展現的就是每一個人所發出來的信息,和對上線人數下線人數進行實時的更新,以前更新是利用一個靜態變量,
可是這樣硬核了一點,這裏正好要用到羣發的功能,因此咱們須要一個list來存放Channel,而後將這個list的size做爲在線人數就行了
羣發就遍歷這個數組,而後writeAndFlush
package com.safelocate.app.nettyServer; import io.netty.channel.*; import io.netty.channel.group.ChannelGroup; import io.netty.channel.group.DefaultChannelGroup; import io.netty.util.concurrent.GlobalEventExecutor; public class ServerHandler extends ChannelInboundHandlerAdapter { private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception{ channels.add(ctx.channel());//加入ChannelGroup System.out.println(ctx.channel().id()+" come into the chattingroom,"+"Online: "+channels.size()); } @Override public void handlerRemoved(ChannelHandlerContext context){ System.out.println(context.channel().id()+" left the chattingroom,"+"Online: "+channels.size()); } @Override public void channelActive(ChannelHandlerContext ctx) { } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { //打印消息而後羣發 System.out.println(msg.toString()); for (Channel channel:channels){ channel.writeAndFlush(msg.toString()); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { System.out.println(ctx.channel().id()+" occurred into error,"+"Online: "+channels.size()); ctx.close(); } }
照樣,打包成jar,java -jar命令運行就行,哦對因爲這裏是本地測試,因此yml文件中的IP應該換成127.0.0.1
接下來是客戶端,首先明確的就是用戶須要輸入信息,因此確定要用到輸入函數,好比Scanner,另外,服務端須要知道每個人的身份,這裏
簡單的用暱稱來代替,在發送的時候將名字也一併發過去,這樣就能簡單分辨是誰發的信息(其實這樣作主要是由於沒來得及寫數據庫升級複雜一點的邏輯)
因此,在以前發信息的函數裏稍微處理一下就行,即增長信息輸入模塊
public static void sendMessage() throws InterruptedException{ // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8)); p.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8)); p.addLast(new ClientHandler()); } }); ChannelFuture future = b.connect(HOST, PORT).sync(); Scanner sca=new Scanner(System.in); while (true){ String str=sca.nextLine();//輸入的內容 if (str.equals("exit")) break;//若是是exit則退出 future.channel().writeAndFlush(name+"-: "+str);//將名字和信息內容一塊兒發過去 } future.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } }
以後把IP改爲127.0.0.1就行,打包的時候,須要在pom文件中添加打包插件,特別注意的是要制定mainClass,否則運行時會報「沒有主清單屬性」
這裏貼上插件配置,這個插件其實對於全部Java程序都適用,由於他會把依賴全帶上
<!-- java編譯插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <configuration> <archive> <manifest> <addClasspath>true</addClasspath> <classpathPrefix>lib/</classpathPrefix> <mainClass>client.Client</mainClass> </manifest> </archive> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <executions> <execution> <id>copy</id> <phase>install</phase> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <outputDirectory>${project.build.directory}/lib</outputDirectory> </configuration> </execution> </executions> </plugin>
打包後以後就是運行了,效果大概是這樣.。。。。。。
哈哈哈哈有時間再完善一下