Я реализовал сервер Netty с таким конвейером:
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new ByteArrayDecoder(), new Byte2MsgHandler()
, new ByteArrayEncoder(), new Msg2ByteHandler(), new MsgDispatcher());
}
Бизнес-логика находится в MsgDispatcher(). Смотри ниже:
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
super.channelRead(ctx, msg);
Msg message = (Msg) msg;
switch (message.messageType) {
case MType.SIGN_UP://sends response to the client
if (userValidator.validate(message.user)) {
userReg.signUp(message.user);
} else {
Msg error = new Msg.Builder().messageType(MType.ERROR)
.errorCode(Constants.USERREG_NULL).build();
ctx.write(error.toByteArray());// write the response back
ctx.flush(); //flush the stream
}
break;
}
}
Я могу успешно отправить данные на сервер с помощью следующего кода из Android:
public void writeAndFlush(Msg msg) throws IOException {
try {
bos.write(msg.toByteArray());
bos.flush();
} catch (IOException e) {
throw new IOException("Exception writing and flushing Msg to network.", e);
}
}
bos — это буферизованный поток вывода из сокета.
Когда я закрываю serversocket после записи, я могу успешно прочитать данные.
Msg error = new Msg.Builder().messageType(MType.ERROR)
.errorCode(Constants.USERREG_NULL).build();
ctx.write(error.toByteArray());// write the response back
ctx.flush(); //flush the stream
ctx.close(); //this result in sucessfull read on android socket.
Но (без «ctx.close() в приведенном выше коде сервера») он зависает в цикле while (код ниже):
public Msg read() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int read = 0;
try {
while ((read = bis.read(buffer, 0, buffer.length)) != -1) {
Log.e("com.traderreg", "" + read);
baos.write(buffer, 0, read);
}
baos.flush();
} catch (IOException e) {
throw new IOException("error reading bytes from socket", e);
}
try {
return wire.parseFrom(baos.toByteArray(), Msg.class);
}catch (IOException e){
throw new IOException("error parsing Msg from socket", e);
}
}
В чем проблема?