Netty应用

Netty是由JBOSS提供的一个java开源框架。Netty提供异步的、事件驱动的网络应用程序框架和工具,用以快速开发高性能、高可靠性的网络服务器和客户端程序。

 

Maven方便版本管理,引入netty依赖就可以把 netty jar包下载 io 目录下了

不用每次导入jar

 

 

 

先写服务端:

class NettyServer {
    def bind(host:String,port:Int):Unit = {
      //配置服务器连接池组

      //用户服务器接收客户端的连接
      
val bossGrop = new NioEventLoopGroup()
      //用于SocketChannel网络读写
      
val workGrop = new NioEventLoopGroup()
      //Netty、启用Nio辅助类
      
try{
      val bootStrap = new ServerBootstrap
      bootStrap.group(bossGrop,workGrop)
         //创建 NioServerSocketChannel
        
.channel(classOf[NioServerSocketChannel])
        //绑定IO事件处理
        
.childHandler(new ChannelInitializer[SocketChannel] {
            override def initChannel(ch: SocketChannel):Unit = {
              ch.pipeline().addLast(
                new ObjectEncoder,
                new ServerHandler
              )
            }
        })
        //绑定端口,调用sync 方法
        
val channelFuture = bootStrap.bind(host,port).sync()
        channelFuture.channel().closeFuture().sync()
      }finally {
        bossGrop.shutdownGracefully()
        workGrop.shutdownGracefully()
      }
    }
}

object NettyServer{
  def main(args:Array[String]): Unit ={
    val host = args(0)
    val port = args(1).toInt
    val nettyServer = new NettyServer
    nettyServer.bind(host,port)
  }
}

 

 

客户端:

 

class NettyClient {

  def connect(host:String,port:Int):Unit = {

    val clientGrop = new NioEventLoopGroup()
    try {
      val bootStrap = new Bootstrap();
      bootStrap.group(clientGrop)
        //创建 NioServerSocketChannel
        
.channel(classOf[NioSocketChannel])
        .handler(new ChannelInitializer[SocketChannel] {
          override def initChannel(ch: SocketChannel): Unit = {
            ch.pipeline().addLast(
              new ObjectEncoder,
              new ClientHandler
            )
          }
        })
      //绑定端口,调用sync 方法
      
val channelFuture = bootStrap.bind(host, port).sync()
      channelFuture.channel().closeFuture().sync()
    }finally {
      clientGrop.shutdownGracefully();
    }
  }
}

object NettyClient{
  def main(args: Array[String]) {
    val host = args(0)
    val port = args(1).toInt
    val client = new NettyClient
    client.connect(host,port)
  }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值