【发布时间】:2018-03-09 03:51:59
【问题描述】:
**chatclient.java**
package com.examplechat;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.sctp.nio.NioSctpChannel;
public class ChatClient {
public static void main(String[] args) throws InterruptedException, IOException {
new ChatClient("localhost", 8000).run();
}
private final String host;
private final int port;
public ChatClient(String host, int port) {
super();
this.host = host;
this.port = port;
}
public void run() throws InterruptedException, IOException {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap()
.group(group)
.channel(NioSctpChannel.class)
.handler(new ChatClientInitilizer());
Channel channel = bootstrap.connect(host, port).sync().channel();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while(true) {
channel.write(in.readLine()+ "\r\n");
}
}
finally {
group.shutdownGracefully(); }
}
}
**ChatServer.java**
package com.examplechat;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class ChatServer {
public static void main(String[] args) throws InterruptedException {
new ChatServer(8000).run();
}
private final int port;
public ChatServer(int port) {
super();
this.port = port;
}
public void run() throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap()
.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChatServerInitializer());
bootstrap.bind(port).sync().channel().closeFuture().sync();
}
finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}}
我正在尝试使用 netty 创建一个聊天应用程序。当我启动聊天服务器 java 应用程序后尝试运行聊天客户端时。它显示了
- 线程“主”io.netty.channel.ChannelException 中的异常:无法 从类类创建通道 io.netty.channel.sctp.nio.NioSctpChannel 位于 io.netty.channel.ReflectiveChannelFactory.newChannel (ReflectiveChannelFactory.java:40)
我什至更改了 pom.xml 的依赖项,但每次运行时我仍然收到相同的错误
更新 Error-1:
Unable to create Channel error已被我自己清除
我自己回答了,请帮我解决第二个问题
Error-2:我收到一个名为 WARNING 的新错误:
Failed to initialize a channel. Closing: [id: 0x9e4e05e0] java.lang.ClassCastException: io.netty.channel.sctp.nio.NioSctpChannel cannot be cast to io.netty.channel.socket.SocketChannel
如果你需要https://github.com/cyborgsri/Chat-Application/tree/master/netty-chat-youtube/src/main/java/com/examplechat,这里是 github 链接。
【问题讨论】:
-
如果你想让我也包含其他文件,请告诉我