Java 在ServerHandler外部发送时,客户端未接收到从服务器发送的消息
我正在尝试将消息从netty服务器发送到连接的客户端 我想做的事和你的很相似。 但是,我使用的是io.netty(带有org.jboss.netty.*包的版本)版本3.10.0.Final 以下是我所做的: java包含初始化服务器的代码Java 在ServerHandler外部发送时,客户端未接收到从服务器发送的消息,java,tcp,client-server,netty,Java,Tcp,Client Server,Netty,我正在尝试将消息从netty服务器发送到连接的客户端 我想做的事和你的很相似。 但是,我使用的是io.netty(带有org.jboss.netty.*包的版本)版本3.10.0.Final 以下是我所做的: java包含初始化服务器的代码 public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (
public static void main(String[] args) throws Exception {
// Configure SSL.
final SslContext sslCtx;
if (SSL) {
SelfSignedCertificate ssc = new SelfSignedCertificate();
sslCtx = SslContext.newServerContext(ssc.certificate(),
ssc.privateKey());
} else {
sslCtx = null;
}
// Configure the server.
ServerBootstrap bootstrap = new ServerBootstrap(
new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
// Configure the pipeline factory.
bootstrap.setPipelineFactory(new TelnetServerPipelineFactory(sslCtx));
// Bind and start to accept incoming connections.
Channel channel = bootstrap.bind(new InetSocketAddress(PORT));
}
TelentServerPipelineFactory.java:
在TelnetServerHandler.java中,我存储了通道有界时的引用:
public class TelnetServerHandler extends SimpleChannelUpstreamHandler {
private static Channel channel;
public static Channel getChannel() {
return channel;
}
.
.
.
.
@Override
public void channelBound(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception {
// TODO Auto-generated method stub
channel = ctx.getChannel();
}
}
我已尝试使用以下代码在TelnetServerHandler外部发送消息:
Scanner scanner = new Scanner(System.in);
System.out.printf("Type message : ");
message = scanner.nextLine();
try{
if(channel.isWritable()){
ChannelFuture future = TelnetServerHandler.getChannel().write(message);
future.sync();
if(!future.isSuccess()){
System.out.println("Send failed : " + future.getCause());
}
}
}catch (Exception e) {
e.printStackTrace();
}
它没有打印错误。当我调试时,future.issuess()返回真值。客户端已连接到服务器。但是,客户端从未从服务器收到消息
我错过什么了吗?非常感谢您的帮助。提前感谢!:) 我找到了解决办法 更改:
ChannelFuture future = TelnetServerHandler.getChannel().write(message);
致:
指出它需要行分隔符,以便解码器正确读取消息
希望有帮助。:)
ChannelFuture future = TelnetServerHandler.getChannel().write(message);
ChannelFuture future = TelnetServerHandler.getChannel().write(message+"\r\n");