Fix AsyncEchoTest

This commit is contained in:
pivovarit 2016-12-04 09:02:10 +01:00
parent 450c250a0f
commit 3a00e57002
2 changed files with 20 additions and 14 deletions

View File

@ -40,18 +40,22 @@ public class AsyncEchoClient {
} }
} }
public String sendMessage(String message) throws Exception { public String sendMessage(String message) {
byte[] byteMsg = message.getBytes(); byte[] byteMsg = message.getBytes();
ByteBuffer buffer = ByteBuffer.wrap(byteMsg); ByteBuffer buffer = ByteBuffer.wrap(byteMsg);
Future<Integer> writeResult = client.write(buffer); Future<Integer> writeResult = client.write(buffer);
//run some code try {
writeResult.get(); writeResult.get();
} catch (Exception e) {
e.printStackTrace();
}
buffer.flip(); buffer.flip();
Future<Integer> readResult = client.read(buffer); Future<Integer> readResult = client.read(buffer);
try {
//run some code readResult.get();
readResult.get(); } catch (Exception e) {
e.printStackTrace();
String echo = new String(buffer.array()).trim(); String echo = new String(buffer.array()).trim();
buffer.clear(); buffer.clear();
return echo; return echo;

View File

@ -58,18 +58,19 @@ public class AsyncEchoServer2 {
@Override @Override
public void completed(Integer result, Map<String, Object> attachment) { public void completed(Integer result, Map<String, Object> attachment) {
String action = (String) attachment.get("action"); Map<String, Object> actionInfo = attachment;
String action = (String) actionInfo.get("action");
if ("read".equals(action)) { if ("read".equals(action)) {
ByteBuffer buffer = (ByteBuffer) attachment.get("buffer"); ByteBuffer buffer = (ByteBuffer) actionInfo.get("buffer");
buffer.flip(); buffer.flip();
attachment.put("action", "write"); actionInfo.put("action", "write");
clientChannel.write(buffer, attachment, this); clientChannel.write(buffer, actionInfo, this);
buffer.clear(); buffer.clear();
} else if ("write".equals(action)) { } else if ("write".equals(action)) {
ByteBuffer buffer = ByteBuffer.allocate(32); ByteBuffer buffer = ByteBuffer.allocate(32);
attachment.put("action", "read"); actionInfo.put("action", "read");
attachment.put("buffer", buffer); actionInfo.put("buffer", buffer);
clientChannel.read(buffer, attachment, this); clientChannel.read(buffer, actionInfo, this);
} }
} }
@ -81,6 +82,7 @@ public class AsyncEchoServer2 {
} }
public static void main(String[] args) { public static void main(String[] args) {
new AsyncEchoServer2(); new AsyncEchoServer2();
} }