gpt4 book ai didi

Java netty客户端无法向服务器发送消息,但telnet到服务器正常

转载 作者:行者123 更新时间:2023-12-01 20:04:04 26 4
gpt4 key购买 nike

我正在学习Java Netty,通过套接字7000制作非常简单的客户端-服务器。服务器正在运行,它将回显从客户端收到的消息。如果我使用 telnet localhost 7000 并向服务器发送消息并接收回显消息,它就可以工作。

但是,对于 Java Netty 客户端,它不起作用。服务器什么也没收到,客户端什么也没发送?当我尝试向控制台添加一些文字时。

以下是此示例的类:

客户端

public final class EchoClient {

public static void main(String[] args) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(
new LoggingHandler(LogLevel.TRACE),
new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Delimiters.lineDelimiter()),
new StringEncoder(),
new StringDecoder(),
new EchoClientHandler());
}
});

// Start the connection attempt.
bootstrap.connect("localhost", 7000).sync().channel().closeFuture().sync();
System.out.println("Message sent successfully.");
} finally {
group.shutdownGracefully();
}
}
}

public class EchoClientHandler extends SimpleChannelInboundHandler<String> {


/**
* Constructor for the class
*
* @param message the message you want to transmit
*/
public EchoClientHandler() {

}

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
String message = "message from client.";
System.out.println("Sending message: " + message);
ctx.write(message);
ctx.flush();
ctx.close();
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
System.out.println("Error caught in the communication service: " + cause);
ctx.close();
}


@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println("Received message: " + msg);
}
}

服务器

    public final class EchoServer {

static final boolean SSL = System.getProperty("ssl") != null;
static final int PORT = Integer.parseInt(System.getProperty("port", "7000"));

public static void main(String[] args) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.TRACE))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(
new LoggingHandler(LogLevel.TRACE),
new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Delimiters.lineDelimiter()),
new StringEncoder(),
new StringDecoder(),
new EchoServerHandler());
}
});

System.out.println("Server is listening on port 7000.");

// Start the server.
ChannelFuture channelFuture = serverBootstrap.bind("localhost", 7000).sync();

// Wait until the server socket is closed.
channelFuture.channel().closeFuture().sync();


} finally {
// Shut down all event loops to terminate all threads.
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}



public class EchoServerHandler extends SimpleChannelInboundHandler<String> {

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
String message = "message from server.";
System.out.println("Sending message: " + message);
ctx.write(message);
ctx.flush();
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
// Close the connection when an exception is raised.
System.out.println("Error in receiving message.");
cause.printStackTrace();
ctx.close();
}

@Override
protected void channelRead0(ChannelHandlerContext ctx, String message) throws Exception {
System.out.println("Received message: " + message);
ctx.write(message);
ctx.flush();
//ctx.close();
}
}

因此,当我运行 EchoServer,然后运行 ​​EchoClient,EchoClient 的输出是

Sending message: message from client.
Message sent successfully.
Then application stopped.

EchoServer 的输出是

Sending message: message from server.

最佳答案

在您的代码中,DelimiterBasedFrameDecoder 处理程序位于解码器/编码器之前。因此,如果传输的消息没有预期的分隔符(例如本例中的换行符),客户端/服务器都将继续等待并认为消息仍在传输。因此,有两种可能的方法可以解决您的问题。

  1. 删除客户端和服务器中的 new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Delimiters.lineDelimiter())
  2. 每次通过 channel 发送消息时,请添加新的行分隔符。否则,消息无法从另一端解码。请在下面找到示例代码

EchoClientHandler 类

public class EchoClientHandler extends SimpleChannelInboundHandler<String> {

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
String message = "message from client.";
System.out.println("Sending message: " + message);
ctx.writeAndFlush(message + System.lineSeparator());
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
System.out.println("Error caught in the communication service: " + cause);
ctx.close();
}

@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println("Received message: " + msg);
}
}

EchoServerHandler 类

  public class EchoServerHandler extends SimpleChannelInboundHandler<String> {

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
String message = "message from server.";
System.out.println("Sending message: " + message);
ctx.writeAndFlush(message + System.lineSeparator());
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
System.out.println("Error in receiving message.");
cause.printStackTrace();
ctx.close();
}

@Override
protected void channelRead0(ChannelHandlerContext ctx, String message) throws Exception {
System.out.println("Received message: " + message);
ctx.writeAndFlush(message + System.lineSeparator());
}
}

服务器输出

Server is listening on port 7000.
Sending message: message from server.
Received message: message from client.

客户端的输出

Sending message: message from client.
Received message: message from server.
Received message: message from client.

关于Java netty客户端无法向服务器发送消息,但telnet到服务器正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47675650/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com