2024年最全Netty案例介绍(websocket服务),面试加分项徐强 百度网盘

最后

开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】

大厂面试问深度,小厂面试问广度,如果有同学想进大厂深造一定要有一个方向精通的惊艳到面试官,还要平时遇到问题后思考一下问题的本质,找方法解决是一个方面,看到问题本质是另一个方面。还有大家一定要有目标,我在很久之前就想着以后一定要去大厂,然后默默努力,每天看一些大佬们的文章,总是觉得只有再学深入一点才有机会,所以才有恒心一直学下去。

  1. 实现基于webSocket的长连接的全双工的交互

  2. 改变Http协议多次请求的约束,实现长连接了, 服务器可以发送消息给浏览器

  3. 客户端浏览器和服务器端会相互感知,比如服务器关闭了,浏览器会感知,同样浏览器关闭了,服务器会感知

2.案例代码实现


2.1 服务端处理器

服务器处理器中我们仅仅需要处理请求和客户端连接和端口的情况,具体如下:

package com.dpb.netty.websocket;

import io.netty.channel.ChannelHandlerContext;

import io.netty.channel.SimpleChannelInboundHandler;

import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.time.LocalDateTime;

/**

  • @program: netty4demo

  • @description: 处理器

  • @author: 波波烤鸭

  • @create: 2019-12-30 22:39

*/

public class SocketServerHandler extends SimpleChannelInboundHandler {

@Override

protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {

// 打印接收到的消息

System.out.println(“服务端接受到的消息:” + textWebSocketFrame.text());

// 返回消息给客户端

channelHandlerContext.writeAndFlush(new TextWebSocketFrame("服务器时间: " + LocalDateTime.now() + " : " + textWebSocketFrame.text()));

}

/**

  • 客户端连接的时候触发

  • @param ctx

  • @throws Exception

*/

@Override

public void handlerAdded(ChannelHandlerContext ctx) throws Exception {

// LongText() 唯一的 ShortText() 不唯一

System.out.println(“handlerAdded:” + ctx.channel().id().asLongText());

System.out.println(“handlerAdded:” + ctx.channel().id().asShortText());

}

/**

  • 客户端断开连接的时候触发

  • @param ctx

  • @throws Exception

*/

@Override

public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {

System.out.println(“handlerRemoved:” + ctx.channel().id().asLongText());

}

@Override

public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

System.out.println(“异常发生了…”);

ctx.close();

}

}

2.2 服务端

服务端代码在原有的基础上需要转换相关的协议,具体如下:

package com.dpb.netty.websocket;

import io.netty.bootstrap.ServerBootstrap;

import io.netty.channel.*;

import io.netty.channel.nio.NioEventLoopGroup;

import io.netty.channel.socket.ServerSocketChannel;

import io.netty.channel.socket.SocketChannel;

import io.netty.channel.socket.nio.NioServerSocketChannel;

import io.netty.handler.codec.http.HttpObjectAggregator;

import io.netty.handler.codec.http.HttpServerCodec;

import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;

import io.netty.handler.logging.LogLevel;

import io.netty.handler.logging.LoggingHandler;

import io.netty.handler.stream.ChunkedWriteHandler;

import java.net.ServerSocket;

/**

  • @program: netty4demo

  • @description: 基于WebSocket协议的服务端

  • @author: 波波烤鸭

  • @create: 2019-12-30 22:31

*/

public class SocketServerDemo {

public static void main(String[] args) throws Exception {

// 1.创建对应的EventLoopGroup对象

EventLoopGroup bossGroup = new NioEventLoopGroup(1);

EventLoopGroup workGroup = new NioEventLoopGroup();

ServerBootstrap bootstrap = new ServerBootstrap();

try{

bootstrap.group(bossGroup,workGroup)

.channel(NioServerSocketChannel.class)

.handler(new LoggingHandler(LogLevel.INFO))

.childHandler(new ChannelInitializer() {

@Override

protected void initChannel(SocketChannel socketChannel) throws Exception {

// websocket 相关的配置

ChannelPipeline pipeline = socketChannel.pipeline();

//因为基于http协议,使用http的编码和解码器

pipeline.addLast(new HttpServerCodec());

//是以块方式写,添加ChunkedWriteHandler处理器

pipeline.addLast(new ChunkedWriteHandler());

/*

说明

  1. http数据在传输过程中是分段, HttpObjectAggregator ,就是可以将多个段聚合

  2. 这就就是为什么,当浏览器发送大量数据时,就会发出多次http请求

*/

pipeline.addLast(new HttpObjectAggregator(8192));

/*

说明

  1. 对应websocket ,它的数据是以 帧(frame) 形式传递

  2. 可以看到WebSocketFrame 下面有六个子类

  3. 浏览器请求时 ws://localhost:8888/hello 表示请求的uri

  4. WebSocketServerProtocolHandler 核心功能是将 http协议升级为 ws协议 , 保持长连接

  5. 是通过一个 状态码 101

*/

pipeline.addLast(new WebSocketServerProtocolHandler(“/hello”));

// 自定义handler,处理业务逻辑

pipeline.addLast(new SocketServerHandler());

}

});

System.out.println(“服务启动了…”);

ChannelFuture future = bootstrap.bind(8888).sync();

future.channel().closeFuture().sync();

}finally {

bossGroup.shutdownGracefully();

workGroup.shutdownGracefully();

}

}

最后

好了,这就是整理的前端从入门到放弃的学习笔记,还有很多没有整理到,我也算是边学边去整理,后续还会慢慢完善,这些相信够你学一阵子了。

做程序员,做前端工程师,真的是一个学习就会有回报的职业,不看出身高低,不看学历强弱,只要你的技术达到应有的水准,就能够得到对应的回报。

开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】

学习从来没有一蹴而就,都是持之以恒的,正所谓活到老学到老,真正懂得学习的人,才不会被这个时代的洪流所淘汰。

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 引入netty-websocket-client依赖 ``` <dependency> <groupId>io.netty</groupId> <artifactId>netty-websocket-client</artifactId> <version>版本号</version> </dependency> ``` 2. 创建WebSocketClient ``` WebSocketClient client = new WebSocketClient(); ``` 3. 设置WebSocketClient的参数 ``` client.setUri("ws://localhost:8080/websocket"); client.setHandshake(new ClientHandshakeBuilder() .addHeader("Origin", "http://localhost:8080") .build()); client.setListener(new WebSocketListener() { @Override public void onOpen(ServerHandshake handshake) { System.out.println("连接成功"); } @Override public void onClose(int code, String reason, boolean remote) { System.out.println("连接关闭"); } @Override public void onMessage(String message) { System.out.println("接收到消息:" + message); } @Override public void onError(Exception ex) { System.out.println("连接出错:" + ex.getMessage()); } }); ``` 4. 启动WebSocketClient ``` client.connect(); ``` 5. 发送消息 ``` String message = "Hello, WebSocket!"; client.sendMessage(message); ``` 6. 关闭WebSocketClient ``` client.close(); ``` 完整示例代码: ``` public class WebSocketClientDemo { public static void main(String[] args) { WebSocketClient client = new WebSocketClient(); client.setUri("ws://localhost:8080/websocket"); client.setHandshake(new ClientHandshakeBuilder() .addHeader("Origin", "http://localhost:8080") .build()); client.setListener(new WebSocketListener() { @Override public void onOpen(ServerHandshake handshake) { System.out.println("连接成功"); } @Override public void onClose(int code, String reason, boolean remote) { System.out.println("连接关闭"); } @Override public void onMessage(String message) { System.out.println("接收到消息:" + message); } @Override public void onError(Exception ex) { System.out.println("连接出错:" + ex.getMessage()); } }); client.connect(); String message = "Hello, WebSocket!"; client.sendMessage(message); client.close(); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值