[英]How to read/write with netty when other side is using readUTF/writeUTF?
I'm trying to communicate with a server that uses DataInputStream.readUTF and DataOutputStream.writeUTF. 我正在尝试与使用DataInputStream.readUTF和DataOutputStream.writeUTF的服务器进行通信。
I did the usual bootstrapping code to setup my client, and set the following pipelinefactory 我执行了通常的引导代码来设置我的客户端,并设置以下管道工厂
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() throws Exception {
return Channels.pipeline(
new LengthFieldBasedFrameDecoder(65536, 0, 2),
new StringDecoder(CharsetUtil.UTF_8),
new StringEncoder(CharsetUtil.UTF_8),
new MyClientHandler());
}
});
in MyClientHandler which extends SimpleChannelUpstreamHandler, I have the following: 在扩展SimpleChannelUpstreamHandler的MyClientHandler中,我具有以下内容:
boolean sent = false; //is this thread safe?
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
logger.log(Level.INFO, e.getMessage().toString());
e.getChannel().write("Hello over there!");
if(!sent){
//do something and set sent
}
}
I managed to receive messages from server successfully, but server is not receiving my "hello over there" message. 我成功地从服务器接收了消息,但是服务器没有收到“在那边的你好”消息。 Not sure what I might have overlooked.
不知道我可能忽略了什么。
Also, notice the boolean sent, can I add such fields and work with them without threading concerns? 另外,请注意发送的布尔值,我可以添加此类字段并在没有线程问题的情况下使用它们吗?
Because the message from the server was able to be received by using LengthFieldBasedFrameDecoder, the message has a length field. 由于可以使用LengthFieldBasedFrameDecoder接收来自服务器的消息,因此该消息具有长度字段。
+--------+----------+
| Length | Message |
+--------+----------+
Therefore, There is a possibility that the server will expect the received message has the length field. 因此,服务器可能会期望收到的消息具有长度字段。 How if the length field is written as follows?
如果length字段写成如下格式怎么办?
+--------+---------------------+
| 0x0011 | "Hello over there!" |
+--------+---------------------+
[sample] [样品]
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
logger.log(Level.INFO, e.getMessage().toString());
byte[] message = "Hello over there!".getBytes("UTF-8");
ChannelBuffer buf = ChannelBuffers.buffer(message.length + 2);
buf.clear();
short len = (short)message.length;
buf.writeShort(len);
buf.writeBytes(message);
e.getChannel().write(buf);
if(!sent){
//do something and set sent
}
}
Yes, you can add the fields to store some state. 是的,您可以添加字段以存储某些状态。 And you need not consider the synchronization of the thread.
而且您无需考虑线程的同步。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.