This commit is contained in:
senft-lap 2012-11-09 22:35:43 +01:00
parent 257dd8c31f
commit d9c483589e
2 changed files with 11 additions and 12 deletions

View File

@ -101,6 +101,8 @@ public class BufferedNetworkStackClient {
InetSocketAddress dest = new InetSocketAddress(host, port);
channel.send(ByteBuffer.wrap(new byte[] { MessageType.CMD_POP }), dest);
buf = ByteBuffer.allocate(BUF_SIZE);
channel.configureBlocking(false);
long time = System.currentTimeMillis() + TIMEOUT;
while (buf.remaining() == BUF_SIZE && System.currentTimeMillis() < time) {
@ -111,10 +113,7 @@ public class BufferedNetworkStackClient {
}
channel.configureBlocking(true);
byte[] receivedData = buf.array();
String strReceived = new String(receivedData).toString().trim();
return strReceived;
return new String(buf.array()).trim();
}
public void print(String host, int port) throws IOException {

View File

@ -12,7 +12,7 @@ import java.util.Stack;
import common.MessageType;
import common.Util;
class BufferedNetworkStack {
public class BufferedNetworkStack {
private DatagramChannel channel;
private ByteBuffer buf;
@ -44,17 +44,14 @@ class BufferedNetworkStack {
for (String s : stack) {
result.append("[").append(s).append("],");
}
result.append('\n');
return result.toString();
}
private void send(String text, SocketAddress client) {
public void stop() {
listenThread.setStopping();
try {
channel.send(ByteBuffer.wrap(text.getBytes()), client);
channel.close();
} catch (IOException e) {
e.printStackTrace();
@ -74,7 +71,7 @@ class BufferedNetworkStack {
try {
client = channel.receive(buf);
} catch (IOException e1) {
e1.printStackTrace();
return;
}
// make buffer readable
@ -101,7 +98,6 @@ class BufferedNetworkStack {
try {
channel.send(buf, client);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
break;
@ -126,6 +122,7 @@ class BufferedNetworkStack {
if (e.isComplete()) {
temp.remove(e);
stack.add(e.toString());
System.out.println("Pushed " + e);
}
break;
}
@ -135,16 +132,19 @@ class BufferedNetworkStack {
case MessageType.CMD_POP:
try {
String popped = stack.pop();
send(popped, client);
channel.send(ByteBuffer.wrap(popped.getBytes()), client);
System.out.println("Pop " + popped);
} catch (EmptyStackException e) {
System.out.println("Received pop but stack is empty");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
break;
case MessageType.CMD_PRINT:
System.out.println(toString());
System.out.println(BufferedNetworkStack.this.toString());
break;
default: