`
347835460
  • 浏览: 1764 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

Netty 5, websocket, websocket群发消息

阅读更多
/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.yxw.task;

import java.net.SocketAddress;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import io.netty.channel.group.ChannelGroup; 
import io.netty.channel.group.DefaultChannelGroup; 
import io.netty.util.concurrent.GlobalEventExecutor;

public class CustomTextFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
	//DefaultChannelGroup recipients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
	private ChannelGroup recipients;

	 
	public CustomTextFrameHandler(ChannelGroup  recipients) {
		this.recipients= recipients;
	}
	
    @Override
    protected void messageReceived(ChannelHandlerContext ctx, TextWebSocketFrame frame) throws Exception {
        String request = frame.text();
        
        //ctx.channel().writeAndFlush(new TextWebSocketFrame(request.toUpperCase()));
        System.out.println("size:"+recipients.size());
        recipients.write(new TextWebSocketFrame(request.toUpperCase()));
        
    }
    
 
    
    @Override
    public void  channelActive(ChannelHandlerContext ctx){
    		recipients.add(ctx.channel());
    		System.out.println("connect:"+recipients.size());
    }
    
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx){
        try {
            recipients.remove(ctx.channel());
            System.out.println("删除channel成功"+recipients.size());
        } catch (Exception ex) {
            System.out.println("删除channel失败"+ex.getMessage());
        }
     }      
  
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}

 以上是 CustomTextFrameHandler.java 内容,

 

/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License, version
 * 2.0 (the "License"); you may not use this file except in compliance with the
 * License. You may obtain a copy of the License at:
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.yxw.task;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
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.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.util.concurrent.GlobalEventExecutor;

import io.netty.channel.group.DefaultChannelGroup; 
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * A WebSocket Server that respondes to requests at:
 *
 * <pre>
 * http://localhost:8080/websocket
 * </pre>
 *
 * The example differs from many of the other examples in Netty in that is does
 * not have an acomponying client. Instead a html page is provided that
 * interacts with this server. <br>
 * Open up the following file a web browser that supports WebSocket's:
 *
 * <pre>
 * example/src/main/resources/websocketx/html5/websocket.html
 * </pre>
 *
 * The html page is very simple were you simply enter some text and the server
 * will echo the same text back, but in uppercase. You, also see getStatus messages
 * in the "Response From Server" area when client has connected, disconnected
 * etc.
 *
 */
public class WebSocketServer {

    private final int port;

    public WebSocketServer(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            final ServerBootstrap sb = new ServerBootstrap();
            sb.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class)
             .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(final SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(
                        new HttpResponseEncoder(),
                        new HttpRequestDecoder(),
                        new HttpObjectAggregator(65536),
                        new WebSocketServerProtocolHandler("/websocket"),
                        new CustomTextFrameHandler(new DefaultChannelGroup(GlobalEventExecutor.INSTANCE)));
                }
            }).option(ChannelOption.SO_BACKLOG, 65536)         
            .childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.TCP_NODELAY, true);
            //.childOption(ChannelOption.SO_BROADCAST, true);
            //bootstrap.setOption("child.reuseAddress", true);		
            //bootstrap.setOption("child.tcpNoDelay", true);		
            //bootstrap.setOption("child.keepAlive", true);
            
            final Channel ch = sb.bind(port).sync().channel();
            System.out.println("Web socket server started at port " + port);

            ch.closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        } else {
            port = 8080;
        }
        new WebSocketServer(port).run();
    }

}

  以上是WebSocketServer.java 的内容, 基本是Netty5 自带的例子改了一点点,

 

 

运行之后,命令行输出:

 

Web socket server started at port 8080

connect:1

size:1

connect:1

size:1

 

 

recipients.size() 始终是1, 于是这个程序不能实现广播, 不知道问题出自哪里?

 

这里忍不住吐槽一下:

1. Netty 不同版本,其接口,方法改变很大,新版本不兼容旧的,一些网上搜到的代码基本都不能用;

2. Netty 上的github上的代码是最新的, 所以想运行example必须用最新版本;

3. 网上的资料太少了;

4. 官方的User guide 和example实在too simple了, 弄了半天还是几个hellow world, 麻烦有点深度写点有用的东西行不, 毕竟项目是用来解决实际问题了, 不是用来写hellow world;

 

 

 

 

 

 

分享到:
评论

相关推荐

    Spring+Netty+WebSocket实例

    这通常涉及设置WebSocket消息的订阅者和发布者。 5. **客户端支持**:在前端,使用JavaScript的WebSocket API或者基于Stomp的库(如`sockjs-client`和`stompjs`)与Spring的WebSocket服务器通信。 6. **测试与调试...

    springboot+netty+websocket+redis

    **SpringBoot+Netty+WebSocket+Redis:构建分布式实时聊天应用** 在当今的互联网世界中,实时通信和数据共享是许多应用程序的核心需求。Spring Boot作为一款流行的Java框架,因其简洁的配置和快速开发特性而备受...

    Spring Boot 整合 Netty + WebSocket 实时消息推送

    在"Spring Boot 整合 Netty + WebSocket 实时消息推送"项目中,我们主要关注以下几个核心知识点: 1. **Spring Boot集成WebSocket**:Spring Boot提供了Spring WebSocket模块,可以方便地集成WebSocket功能。通过...

    netty+websocket实现心跳和断线重连

    在本文中,我们将深入探讨如何利用 Netty 和 WebSocket 实现心跳检测和断线重连机制。 首先,我们需要理解 WebSocket 协议。WebSocket 是一种在单个 TCP 连接上进行全双工通信的协议,它为客户端和服务器提供了低...

    netty-websocket.zip

    5. **无消息互动判断网络断开**:如果在设定的心跳间隔时间内,服务器或客户端都没有收到对方的心跳包,那么可以认为网络连接出现问题,此时服务端应关闭长连接。 在压缩包中的"netty-websocket"可能包含以下内容:...

    netty+websocket聊天室例子(可私聊)

    Netty提供了`WebSocketServerFrameHandler`,用于处理接收到的WebSocket帧,你可以根据需要实现这个接口来处理不同的WebSocket消息类型。 **构建聊天室** 1. **服务器端** - 首先,你需要创建一个`...

    基于netty的websocket开发小结

    WebSocketClientHandler同样是我们自定义的处理器,它负责发送和接收WebSocket消息。 在实际应用中,我们可能还需要处理心跳、异常、超时等问题。Netty提供了WebSocketFrameDecoder和WebSocketFrameEncoder帮助解码...

    SpringBoot中使用Netty开发WebSocket服务改造多线程群发消息示例代码

    SpringBoot中使用Netty开发WebSocket服务改造多线程群发消息示例代码: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/131681393

    netty-websocket-example 基于netty的websocket实现示例

    1. **WebSocket 服务器端实现**:Netty 提供了 WebSocketServerHandler 类,我们可以继承并覆盖其方法来处理 WebSocket 连接的建立、关闭以及接收到的消息。例如,我们需要实现 `channelActive()` 方法来处理连接...

    基于netty+websocket+springboot的实时聊天系统项目源码.zip

    1、基于netty+websocket+springboot的实时聊天系统项目源码.zip 2、该资源包括项目的全部源码,下载可以直接使用! 3、本项目适合作为计算机、数学、电子信息等专业的课程设计、期末大作业和毕设项目,作为参考资料...

    毕设项目:基于netty+websocket+springboot的实时聊天系统.zip

    毕设项目:基于netty+websocket+springboot的实时聊天系统 毕设项目:基于netty+websocket+springboot的实时聊天系统 毕设项目:基于netty+websocket+springboot的实时聊天系统 毕设项目:基于netty+websocket+...

    基于netty的websocket

    8. **WebSocket工具**: 除了Netty自带的WebSocket处理器,还有一些第三方库可以帮助我们更方便地处理WebSocket,例如Spring Framework的WebSocket支持,可以简化WebSocket的集成和管理。 9. **源码分析**: 博文链接...

    基于netty搭建websocket实现消息主动推送【Springbooot项目,可直接使用】

    Netty的WebSocketServer通常包括几个关键组件:`ServerBootstrap`用于配置服务器,`ChannelInitializer`用于初始化连接通道,`WebSocketServerProtocolHandler`处理WebSocket升级请求,以及自定义的`...

    netty+websocket通讯例子

    在本文中,我们将深入探讨如何利用 Netty 和 WebSocket 技术实现通信,以及 `callServer` 文件可能包含的内容。 WebSocket 是一种在单个 TCP 连接上进行全双工通信的协议,它为 Web 应用程序提供了低延迟、双向通信...

    使用Netty搭建WebSocket服务器,可修改单包大小限制

    Netty是一个高性能、异步事件驱动的网络应用程序框架,它非常适合用来构建WebSocket服务器。 Netty提供了WebSocketServerProtocolHandler来处理WebSocket协议,但在默认情况下,它会对接收到的数据包大小进行限制。...

    netty-websocket-proxy-1.3.1-bin.zip

    5. **示例代码**:可能包含一些示例项目,展示如何集成和使用 Netty WebSocket 代理服务。 6. **许可证文件**:说明软件的授权和使用条款。 关于 Netty 实现 WebSocket 代理的知识点: 1. **异步编程模型**:Netty...

    基于SpringBoot与Netty的WebSocket弹幕系统设计源码

    后端使用SpringBoot 2.4.3进行开发,利用Netty实现WebSocket通信,同时结合Redis进行数据存储和处理。前端采用Vue框架,通过WebSocket与后端进行实时数据通信。系统还采用DFA算法模型对敏感词进行过滤,确保内容的...

    netty案例,netty4.1中级拓展篇五《基于Netty搭建WebSocket,模仿微信聊天页面》源码

    netty案例,netty4.1中级拓展篇五《基于Netty搭建WebSocket,模仿微信聊天页面》源码 ...

    netty实现websocket例子

    Netty提供了WebSocketServerProtocolHandler类来处理WebSocket的握手和消息传输。在创建WebSocket服务器时,我们需要定义一个ChannelInboundHandlerAdapter的子类,重写其中的方法来处理接收到的消息和连接事件。...

Global site tag (gtag.js) - Google Analytics