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) } } |