我正在为一个网络游戏运行一个Netty服务器,但是我正在经历一些奇怪的行为:
随机地,通道就会停止从服务器写入,即用户仍然被连接并且接收到数据,但是输出数据不能到达客户端。
我花了时间调试这个问题,我发现channel.isWriteable()正在返回false,以便将客户端与问题连接起来。
有人能照亮为什么会发生这种事吗?
一个频道不能写更多的原因是什么?
顺便说一句,这种情况也发生在本地主机连接上。
public ChannelFuture write(Packet message) {
ioWrite++;
if (!channel.isConnected()) {
System.err.println("Trying to write to bad channel");
return null;
}
if (!channel.isWritable()) {
System.err.println("Channel buffer is full?");
}
if ((channel != null) && channel.isConnected()) {
return channel.write(message);
}
return null;
}编码器:
public class GameProtocolEncoder extends OneToOneEncoder {
private ChannelBuffer response;
protected Object encode(ChannelHandlerContext channelHandlerContext, Channel channel, Object o) throws Exception {
Packet p = (Packet) o;
try {
byte[] data = p.getData();
int dataLength = p.getLength();
if (p.getLength() > 5000) {
System.err.println("unable to write data chunk to large");
return null;
}
if (!p.isBare()) {
int siz = 0;
siz += (p.getSize() == Packet.Size.VariableShort)
? 2
: 1;
siz += (p.getId() > 128)
? 2
: 1;
response = ChannelBuffers.buffer(siz + p.getLength());
int id = p.getId();
if (id< 128) {
response.writeByte(id);
} else {
response.writeByte((byte) ((id >> 8) + 128));
response.writeByte((byte) (id & 0xFF));
}
if (p.getSize() != Packet.Size.Fixed) { // variable length
if (p.getSize() == Packet.Size.VariableByte) {
if (dataLength > 255) { // trying to send more data then we can represent with 8 bits!
throw new IllegalArgumentException("Tried to send packet length " + dataLength
+ " in 8 bits [pid=" + p.getId() + "]");
}
response.writeByte((byte) dataLength);
} else if (p.getSize() == Packet.Size.VariableShort) {
if (dataLength > 5000) {
throw new IllegalArgumentException("Tried to send packet length to big: " + id);
}
response.writeShort((short) dataLength);
}
}
} else {
response = ChannelBuffers.buffer(dataLength);
}
response.writeBytes(p.getData());
return response;
} catch (Exception e) {
Logger.err("Error handling message: " + p);
Logger.err(e);
}
return null;
}发布于 2015-01-15 15:21:51
我认为问题在于你没有冲洗英吉利海峡。尝试替换channel.write(.)Channel.writeAndFlush(.)
发布于 2015-01-14 21:23:49
当通道的套接字发送缓冲区被填满时,通道不再可写,而当发送方超过接收方时,则会发生这种情况。
如果经常发生这种情况,您可能希望加快接收代码的速度,但通常情况下,它可以在任何时候发生,而您所能做的就是推迟写入,直到通道再次变得可写。
https://stackoverflow.com/questions/27952122
复制相似问题