2024年Netty案例介绍(websocket服务)(1),2024年最新程序员面试基本知识

结束

一次完整的面试流程就是这样啦,小编综合了腾讯的面试题做了一份前端面试题PDF文档,里面有面试题的详细解析,分享给小伙伴们,有没有需要的小伙伴们都去领取!

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

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();

}

}

}

2.3 客户端实现

在客户端中我们就简单的实现一个HTML页面,在其中发送websocket协议相关的请求,然后接受相关的消息,如下,注意注释

websocket案例测试
  • 26
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值