- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
这实际上是我在这里发表的第一篇文章,一段时间以来我一直在努力解决这个问题,但我最终决定加入 flag 并尝试在这个主题上获得一些帮助。
所以我有一个客户端和一个服务器,它们是在回声客户端/服务器和安全聊天客户端/服务器之后建模的。我对聊天的 SSL 部分不感兴趣,使用 echo 只是为了确保我从客户端/服务器获得响应。我将在这篇文章的底部添加所有相关代码。我现在遇到的问题是,我可以在客户端连接时从服务器向客户端发送消息,但是在服务器向客户端发送初始消息后,我无法从客户端向服务器发送消息。从服务器发送的消息是:
Welcome to the server!
客户端的消息是
test
我应该知道我收到了来自客户端的消息,因为它应该回显
[You] test
我知道服务器会看到客户端,它会给我状态更新,但由于某种原因我无法向服务器发送消息。现在问一个关于这个的问题......我目前正在使用 StringDecoder 和 StringEncoder 作为解码器和编码器......如果你正在制作游戏(这就是我正在做的)并且您将拥有诸如登录、玩家移动、世界更新等内容……发送字符串是执行此操作的最佳方式吗?我知道我经常看到字节流,在我的编程课上,我讲过如何操作字节流,但我仍然不是 100% 熟悉它们。如果字节流是执行此操作的更好/最好的方法,那么有人可以详细解释它是如何操作字节流以处理不同项目的。
如前所述,这是客户端中一切的开始:
public class Client {
public Client() {
// Initialize the window
GameWindow.init();
// Initialize the server connection
ClientHandler.init();
}
public static void main(String[] args) throws Exception {
// Set a default server address if one isn't specified in the arguments
if (args.length < 2 || args.length > 3) {
System.err.println("Usage: " + Client.class.getSimpleName() + " <host> <port> [<first message size>]");
System.err.println("Using default values.");
} else {
// Parse arguments
Settings.host = args[0];
Settings.port = Integer.parseInt(args[1]);
}
// start client
new Client();
}
客户端处理程序:
package simple.client.net;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.WriteCompletionEvent;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import simple.client.Settings;
public class ClientHandler extends SimpleChannelUpstreamHandler {
private static final Logger logger = Logger.getLogger(ClientHandler.class.getName());
public static Channel channel;
public ClientHandler() {
}
public static void init() {
// Configure the client.
ClientBootstrap bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
// Set up the pipeline factory.
bootstrap.setPipelineFactory(new ClientPipelineFactory());
// Start the connection attempt.
ChannelFuture future = bootstrap.connect(new InetSocketAddress(Settings.host, Settings.port));
// Wait until the connection is closed or the connection attempt fails.
channel = future.awaitUninterruptibly().getChannel();
// This is where the test write is <<------
ChannelFuture test = channel.write("test");
if (!future.isSuccess()) {
future.getCause().printStackTrace();
bootstrap.releaseExternalResources();
return;
}
}
@Override
public void channelBound(ChannelHandlerContext ctx, ChannelStateEvent e) {
System.out.println("Bound: " + e.getChannel().isBound());
}
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
System.out.println("Connected: " + e.getChannel().isConnected());
System.out.println("Connected: " + e.getChannel().getRemoteAddress());
}
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) {
System.out.println("Closed: " + e.getChannel());
}
@Override
public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
System.out.println("Disconnected: " + e.getChannel());
}
@Override
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) {
System.out.println("Open: " + e.getChannel().isOpen());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
System.out.println("Error: " + e.getCause());
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
System.out.println("Message: " + e.getMessage());
}
}
最后是 ClientPipeline:
package simple.client.net;
import static org.jboss.netty.channel.Channels.*;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder;
import org.jboss.netty.handler.codec.frame.Delimiters;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;
public class ClientPipelineFactory implements ChannelPipelineFactory {
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline();
pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast("handler", new ClientHandler());
return pipeline;
}
}
服务器端:
package simple.server;
public class Server {
public static void main(String[] args) throws Exception {
ServerChannelHandler.init();
}
}
服务器 channel 处理器:
package simple.server;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.logging.Logger;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
public class ServerChannelHandler extends SimpleChannelHandler {
private static final Logger logger = Logger.getLogger(ServerChannelHandler.class.getName());
private static ChannelGroup channels;
private static ServerBootstrap bootstrap;
public ServerChannelHandler() {
}
/**
* Initialize the Server Channel Handler
*/
public static void init() {
// create a channels group to add incoming channels to
channels = new DefaultChannelGroup();
// create the server bootstrap (fancy word for pre-made server setup)
bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
// set the server pipeline factory
bootstrap.setPipelineFactory(new ServerPipelineFactory());
// server settings
bootstrap.setOption("keepAlive", true);
// bind the server to the port
bootstrap.bind(new InetSocketAddress(Settings.PORT_ID));
}
@Override
public void channelBound(ChannelHandlerContext ctx, ChannelStateEvent e) {
System.out.println("Bound: " + e.getChannel());
}
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
System.out.println("Connected: " + e.getChannel());
channels.add(e.getChannel());
e.getChannel().write("Welcome to the test server!\n\r");
}
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) {
System.out.println("Closed: " + e.getChannel());
}
@Override
public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
System.out.println("Disconnected: " + e.getChannel());
}
@Override
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) {
System.out.println("Open: " + e.getChannel());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
System.out.println("Error: " + e.getCause());
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
System.out.println("Message: " + e.getMessage());
for (Channel c : channels) {
if (e.getMessage().equals("shutdown")) {
shutdown();
}
if (c != e.getChannel()) {
c.write("[" + e.getChannel().getRemoteAddress() + "] " + e.getMessage() + "\n\r");
} else {
c.write("[You] " + e.getMessage() + "\n\r");
}
}
}
/**
* Shuts down the server safely
*/
public static final void shutdown() {
channels.close();
bootstrap.releaseExternalResources();
System.exit(0);
}
}
服务器管道工厂:
package simple.server;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder;
import org.jboss.netty.handler.codec.frame.Delimiters;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;
import simple.server.decoder.Decoder;
import simple.server.encoder.Encoder;
public class ServerPipelineFactory implements ChannelPipelineFactory {
@Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast("handler", new ServerChannelHandler());
return pipeline;
}
}
再一次感谢大家在理解这一点上能给我的任何帮助。
最佳答案
您忘记将 \r\n
附加到 "test"
。它应该是:channel.write("test\r\n")
.`
从管道中可以看出,解码部分由两个处理程序组成。第一个将接收到的数据拆分并合并到一行字符串中,并去除以它结尾的行。第二个将单行字符串转换为 java.lang.String
。
在编码方面,只有一个处理程序,它将 java.lang.String
转换为 ByteBuf
,仅此而已。也许最好引入一个名为 LineEncoder
、LineDecoder
和 LineCodec
的处理程序来完成通常预期的工作:https://github.com/netty/netty/issues/1811
关于java - Netty 客户端到服务器消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13923032/
我正在尝试使用 Netty 构建一个反向代理,并且我想保留一个到后端服务器的开放套接字池,而不是每个传入套接字都需要一个从反向代理到后端服务器的新套接字。 你能用 Netty 做到这一点吗?如何? 谢
从 Netty 3.5.x 到 Netty 4 性能提升了多少?有数据吗? 最佳答案 目前没有太大改进。不过,它的 GC 开销要少得多。一旦实现缓冲池,我相信吞吐量也会变得更好。目前,吞吐量增益约为
我正在尝试关闭与它建立连接的 Netty 服务器,但它只是挂起。这就是我所做的。 在一台机器上启动服务器,在另一台机器上启动客户端。 从客户端向服务器发送一条消息,我得到响应。 使用 Ctrl-C 关
doc说“每个轮子的默认滴答数(即轮子的大小)是 512。如果你要安排很多超时,你可以指定一个更大的值。” 这是否意味着默认情况下它只能处理 512 次超时?如果我想要 25 秒的 10 万次超时(对
我正在使用 netty 4.0.25Final 编写一个 netty HTTP 服务器。我需要根据 HTTP GET 请求中的一些参数在管道中添加各种处理程序。 pipeline.addLast(ne
我现在将 Netty 用于一些服务器端组件有一段时间了,我对此感到非常满意。因此,为了我自己的方便,我还想在客户端使用它,但我想保持小程序的占用空间(在这种情况下)尽可能小。我需要从 Netty 那里
有没有办法告诉 netty 停止监听和接受套接字上的新连接,但要完成当前连接上的任何正在进行的工作? 最佳答案 您可以关闭 ServerSocketChannel创建者 ChannelFactory
我用响应式(Reactive) mongo 创建了简单的 Webflux (kotlin) 应用程序。 Controller 有一个 GET 方法,即返回 Flow(来自一个集合的 2 个对象)。 我
我有一个新项目,我将第一次使用 Netty (v4.0.4)。我将拥有一个拥有数万个连接客户端的服务器。服务器将向这些客户端发送命令并应该接收响应。 查看 API 和在线示例,我不确定如何从服务器的角
与 boost.asio 不同,netty 没有类似 read 的方法。以下情况不方便:管理节点管理一些节点,客户端连接到管理节点以检索驻留在节点中的信息。当管理节点收到客户端的请求后,向对应的节点发
我正在编写一个应用程序,其中客户端和服务器都是使用 Netty 编写的,并且服务器应该(显然)同时支持多个客户端。我试图通过创建 1000 个客户端共享一个 EventLoopGroup 并在一台机器
如果我在 Netty 101 期间睡着了,请原谅我,但我想知道是否有一种“正确”的方式来等待 Netty 完成多步骤连接过程。假设我有一个应用程序,其过程如下所示: 打开实际连接。 执行 TLS 握手
将 Netty ChannelBuffer 转换为 String 就像在 ChannelBuffer 上调用 .toString(UTF_8) 一样简单。如何从字符串创建 ChannelBuffer?
在 Netty 3 中,我们可以这样做: Channel.setReadable(false); Channel.setReadable(true); 我读了: http://netty.io/new
我知道 Storm 现在运行在 Netty 上用于节点之间的通信? Apache Spark 是否也使用 Netty?如果真是这样,那么是以哪种方式? 最佳答案 Spark使用Akka Actor进行
很难说出这里问的是什么。这个问题是模棱两可的、模糊的、不完整的、过于宽泛的或修辞的,无法以目前的形式得到合理的回答。如需帮助澄清这个问题以便重新打开它,visit the help center .
我真的很困惑老板组的线程数。我想不出我们需要多个老板线程的情况。在 do we need more than a single thread for boss group? Netty 的创建者说,如
我已将其添加到我的管道中,并且 LoggingHandler 正在捕获其事件,但是由于事件系统从 Netty 3 更改为 4,我该如何处理这些事件,因为 IdleStateAwareUpstreamH
有没有办法在 channel 上保持状态。我正在编写一个聊天服务器,我想保留有关 channel 所属用户的信息。我在想也许 Channel 会提供一种方法来存储用户对象,但我看不到。有没有办法在不需
我有一个 netty channel ,我想在底层套接字上设置超时(默认设置为 0 )。 超时的目的是,如果 15 分钟内没有发生任何事情,则未使用的 channel 将被关闭。 虽然我没有看到任何配
我是一名优秀的程序员,十分优秀!