欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring Boot集成netty实现客户端服务端交互示例详解

程序员文章站 2024-02-26 15:13:28
前言 netty 是一个高性能的 nio 网络框架,本文主要给大家介绍了关于springboot集成netty实现客户端服务端交互的相关内容,下面来一起看看详细的介绍...

前言

netty 是一个高性能的 nio 网络框架,本文主要给大家介绍了关于springboot集成netty实现客户端服务端交互的相关内容,下面来一起看看详细的介绍吧

看了好几天的netty实战,慢慢摸索,虽然还没有摸着很多门道,但今天还是把之前想加入到项目里的

一些想法实现了,算是有点信心了吧(讲真netty对初学者还真的不是很友好......)

首先,当然是在springboot项目里添加netty的依赖了,注意不要用netty5的依赖,因为已经废弃了

<!--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的服务器,这里服务端的逻辑就是将客户端发来的信息返回回去

因为采用依赖注入的方法实例化netty,所以加上@component注释

package com.safelocate.app.nettyserver;

import io.netty.bootstrap.serverbootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.nioeventloopgroup;
import io.netty.channel.socket.nio.nioserversocketchannel;
import org.apache.log4j.logger;
import org.springframework.stereotype.component;

import java.net.inetsocketaddress;

@component
public class nettyserver {
 //logger
 private static final logger logger = logger.getlogger(nettyserver.class);
 public void start(inetsocketaddress address){
 eventloopgroup bossgroup = new nioeventloopgroup(1);
 eventloopgroup workergroup = new nioeventloopgroup();
 try {
  serverbootstrap bootstrap = new serverbootstrap()
   .group(bossgroup,workergroup)
   .channel(nioserversocketchannel.class)
   .localaddress(address)
   .childhandler(new serverchannelinitializer())
   .option(channeloption.so_backlog, 128)
   .childoption(channeloption.so_keepalive, true);
  // 绑定端口,开始接收进来的连接
  channelfuture future = bootstrap.bind(address).sync();
  logger.info("server start listen at " + address.getport());
  future.channel().closefuture().sync();
 } catch (exception e) {
  e.printstacktrace();
  bossgroup.shutdowngracefully();
  workergroup.shutdowngracefully();
 }
 }

}

当然,这里的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命令,可以看到程序已经跑起来了,等待客户端连接交互

Spring Boot集成netty实现客户端服务端交互示例详解

之后就是写客户端了,客户端其实是依葫芦画瓢,跟上面类似

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",可以看到客户端已经收到服务器发来的信息


Spring Boot集成netty实现客户端服务端交互示例详解

然后再看服务端,也有相应的信息打印

Spring Boot集成netty实现客户端服务端交互示例详解

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。