用java写一个netty的即时通讯demo
时间: 2024-05-02 12:21:05 浏览: 134
即时通信netty的小demo
4星 · 用户满意度95%
抱歉,作为AI语言模型,我无法编写实际的代码,但是我可以向您提供一些基本的步骤和代码示例,以便您开始编写Netty即时通信Demo。
1. 导入Netty依赖
在您的Maven项目中,将以下依赖项添加到pom.xml文件中:
```
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.65.Final</version>
</dependency>
```
2. 创建服务器
创建一个Netty服务器来接收客户端连接并处理消息:
```
public class ChatServer {
private final int port;
public ChatServer(int port) {
this.port = port;
}
public void start() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new ChatServerHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture f = b.bind(port).sync();
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
}
```
3. 创建消息处理器
创建一个消息处理器来处理客户端发送的消息:
```
public class ChatServerHandler extends SimpleChannelInboundHandler<String> {
private static final Map<Channel, String> channelMap = new ConcurrentHashMap<>();
private static final String CHAT_SERVER = "ChatServer";
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
String remoteAddress = channel.remoteAddress().toString();
channelMap.put(channel, remoteAddress);
System.out.println("Client " + remoteAddress + " connected to " + CHAT_SERVER);
super.channelActive(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
String remoteAddress = channel.remoteAddress().toString();
channelMap.remove(channel);
System.out.println("Client " + remoteAddress + " disconnected from " + CHAT_SERVER);
super.channelInactive(ctx);
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, String message) throws Exception {
Channel channel = ctx.channel();
String remoteAddress = channel.remoteAddress().toString();
System.out.println("Received message from " + remoteAddress + ": " + message);
for (Channel ch : channelMap.keySet()) {
if (ch != channel) {
ch.writeAndFlush("[" + remoteAddress + "]: " + message + "\n");
}
}
}
}
```
4. 创建客户端
创建一个Netty客户端来连接服务器并发送消息:
```
public class ChatClient {
private final String host;
private final int port;
public ChatClient(String host, int port) {
this.host = host;
this.port = port;
}
public void start() throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new ChatClientHandler());
}
});
ChannelFuture f = b.connect(host, port).sync();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String message = in.readLine();
if (message == null) {
break;
}
f.channel().writeAndFlush(message + "\n");
}
f.channel().closeFuture().sync();
} finally {
group.shutdownGracefully();
}
}
}
```
5. 创建客户端消息处理器
创建一个消息处理器来处理从服务器接收的消息:
```
public class ChatClientHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String message) throws Exception {
System.out.println(message);
}
}
```
6. 运行Demo
在主方法中创建服务器和客户端实例并运行它们:
```
public class ChatDemo {
private static final int PORT = 8080;
private static final String HOST = "localhost";
public static void main(String[] args) throws Exception {
ChatServer server = new ChatServer(PORT);
ChatClient client = new ChatClient(HOST, PORT);
new Thread(() -> {
try {
server.start();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
client.start();
}
}
```
现在您已经有了一个简单的Netty即时通信Demo,可以在本地计算机上启动服务器和客户端,并通过控制台输入消息进行通信。
阅读全文