写个完整全面的,是服务端,主动给客户端发
时间: 2024-10-25 15:13:06 浏览: 13
在Java中,如果你想要服务端主动向客户端发送数据,通常是在一个长连接或定时任务场景下。比如WebSocket服务器就是常见的主动推送的例子。下面是一个简单的基于`Netty`框架实现的WebSocket服务端,它可以主动向客户端发送消息:
首先,你需要在项目中引入Netty库,可以通过Maven或Gradle添加依赖。
```xml
<!-- Maven -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.x.y</version> <!-- 使用最新的稳定版本 -->
</dependency>
// Gradle
implementation 'io.netty:netty-all:x.y.z'
```
然后,创建一个WebSocket服务器:
```java
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
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.websocketx.TextWebSocketFrame;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
public class WebSocketServer {
private static final int PORT = 8080;
public static void main(String[] args) {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline()
.addLast(new TextWebSocketFrameDecoder())
.addLast(new TextWebSocketFrameEncoder())
.addLast(new WebSocketServerHandler());
}
});
ChannelFuture f = b.bind(PORT).sync();
// 主动向所有在线连接发送消息
for (Object channel : b.childGroup().allChannels()) {
WebSocketServerHandler handler = (WebSocketServerHandler) ((Channel) channel).pipeline().get(WebSocketServerHandler.class);
handler.sendMessageToAll("Server message to all clients");
}
// 等待关闭
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
}
class WebSocketServerHandler extends ChannelInboundHandlerAdapter {
//...
public void sendMessageToAll(String message) {
for (WebSocketSession session : sessions) {
session.textMessage(message);
}
}
//...
}
```
在这个例子中,`WebSocketServerHandler`负责接收和处理WebSocket连接,`sendMessageToAll`方法会遍历所有在线的`WebSocketSession`,并向每个客户端发送一条消息。
阅读全文