Netty实现客户端与服务端通信
程序员文章站
2022-06-06 08:29:53
...
实现一个客户端与服务端通信的程序,可以使用socket网络编程来实现,而Netty作为一个封装了JDK的NIO通讯的异步事件驱动的网络应用框架,也同样可以实现。
1.创建Maven项目,在pom文件中引入Netty依赖。
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.6.Final</version>
</dependency>
2.创建服务端NettyServer.java
,代码如下:
public class NettyServer {
public static void main(String[] args) {
//引导类,引导我们进行服务端的启动工作
ServerBootstrap serverBootstrap=new ServerBootstrap();
//监听端口,创建新连接的线程组
NioEventLoopGroup boos=new NioEventLoopGroup();
//表示处理每一条连接的数据读写的线程组
NioEventLoopGroup worker=new NioEventLoopGroup();
serverBootstrap
//给引导类配置两大线程,这个引导类的线程模型也就定型了
.group(boos,worker)
//指定我们服务端的IO模型为NIO,NioServerSocketChannel是对NIO类型的连接的抽象,类似于ServerSocket
.channel(NioServerSocketChannel.class)
//指定在服务端启动过程中的一些逻辑,通常情况下我们用不着这个方法
.handler(new ChannelInitializer<NioServerSocketChannel>() {
protected void initChannel(NioServerSocketChannel nioServerSocketChannel) throws Exception {
System.out.println("服务端启动中...");
}
})
//定义后续每条连接的数据读写,业务处理逻辑,NioSocketChannel是Netty对NIO类型的连接的抽象,类似于Socket
.childHandler(new ChannelInitializer<NioSocketChannel>() {
protected void initChannel(NioSocketChannel ch) throws Exception {
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
//输出从客户端发送过来的消息
System.out.println(msg);
}
});
}
})
//绑定一个8010端口启动
.bind(8010)
//监听端口是否绑定成功
.addListener(new GenericFutureListener<Future<? super Void>>() {
public void operationComplete(Future<? super Void> future) throws Exception {
if(future.isSuccess()){
System.out.println("端口绑定成功!");
}else{
System.out.println("端口绑定失败!");
}
}
});
}
}
3.创建客户端NettyClient.java
,代码如下:
public class NettyClient {
public static void main(String[] args) throws InterruptedException {
Bootstrap bootstrap=new Bootstrap();
NioEventLoopGroup group=new NioEventLoopGroup();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<Channel>() {
protected void initChannel(Channel channel) throws Exception {
channel.pipeline().addLast(new StringEncoder());
}
});
//获取连接通道
Channel channel=bootstrap.connect("127.0.0.1",8010).channel();
while(true){
//循环向服务端发送消息
channel.writeAndFlush(new Date()+":hello Jetty!");
Thread.sleep(2000);
}
}
}
4.启动服务端,控制台输出如下信息:
服务端启动中...
端口绑定成功!
5.启动客户端,服务端控制台输出如下信息:
Wed Dec 18 18:31:35 CST 2019:hello Jetty!
Wed Dec 18 18:31:37 CST 2019:hello Jetty!
Wed Dec 18 18:31:39 CST 2019:hello Jetty!
...
可以看到服务端已经接收到客户端发送过来的消息,并且因为客户端的循环发送不断的在控制台打印消息。
上一篇: linux c socket编程回顾二:简单服务端、客户端
下一篇: 班戈县