1
我想弄清楚如何使用netty nio服务器和从here找到的客户端代码创建聊天。我实际上想要弄清楚我究竟能够如何使用从客户端和服务器接收到的消息。然而从服务器netty nio java接收消息
public class EchoClient {
public String host;
public int port;
public EchoClient(String host, int port) {
this.host = host;
this.port = port;
}
public void send(String msg) throws InterruptedException {
EventLoopGroup eventGroup = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(eventGroup)
.remoteAddress(host, port)
.channel(NioSocketChannel.class) // TCP server socket
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(
// break stream into "lines"
new LineBasedFrameDecoder(EchoServerHandler.LINE_MAX, false, true),
new StringDecoder(CharsetUtil.UTF_8),
new StringEncoder(CharsetUtil.UTF_8),
new EchoClientHandler()
);
}
});
ChannelFuture f = bootstrap.connect().sync();
System.out.println("Connected!");
f.channel().writeAndFlush(msg).sync();
System.out.print("Sent: " + msg);
f.channel().closeFuture().sync();
eventGroup.shutdownGracefully().sync();
System.out.println("Done.");
}
public static void main(String[] args) throws InterruptedException {
EchoClientHandler temp = new EchoClientHandler(); //how can i have access to this variable and the returned message?
String host ="127.0.0.1";
int port = 8080;
EchoClient client = new EchoClient(host, port);
client.send("Hello world!\n");
temp.message?
}
}
在代码在这里有一个打印的消息,我已经在服务器中发现了哪些类型的接收邮件的服务器下面的代码:
public class EchoClientHandler extends ChannelInboundHandlerAdapter {
public String message;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("Got reply: " + msg.toString().trim());
message = msg.toString().trim();
ctx.disconnect();
}
// How to store the message variable and use it from my main function?????
}
这个代码代表的echoClient Object msg如何与接收到的消息连接?我想如何使用它?
编辑:public String message
在channelRead
有一个值,但是,主要是空的。我怎样才能正确传递价值?猜测EchoClientHandler和EchoClient与EchoClient中的主要函数不同。但是,有没有一种方法可以从我的主函数中读取从EchoClientHandler获得的接收到的消息?
对不起,我真的没有跟着你。我想从客户端的主要功能中读取消息。在连接之后,什么打印来自main而不是来自channelRead的消息或者将其解析为新的变量。 –
请您详细说明一下吗?包括整个代码表客户端都有更新的问题。 –
'channelRead'和'main'方法在不同的线程中(异步IO)。您可以使用中间数据类型来存储和从'EchoClientHandler'类中检索。 –