Skip to content

Instantly share code, notes, and snippets.

@daeyun
Created November 22, 2013 10:45
Show Gist options
  • Save daeyun/7597989 to your computer and use it in GitHub Desktop.
Save daeyun/7597989 to your computer and use it in GitHub Desktop.
public class Main {
public static void main(String[] args) throws IOException {
SocketChannel socketChannel = SocketChannel.open();
try {
socketChannel.connect(new InetSocketAddress("localhost", 10100));
} catch (IOException e) {
// Connection error
}
ByteBuffer buf = ByteBuffer.allocateDirect(1024);
try {
while (true) {
buf.clear();
int numBytesRead = socketChannel.read(buf);
if (numBytesRead == -1) {
break;
} else {
buf.flip();
System.out.println(toString(buf));
}
}
} catch (IOException e) {
// Connection may have been closed
}
socketChannel.close();
}
public static String toString(ByteBuffer bb) {
final byte[] bytes = new byte[bb.remaining()];
bb.duplicate().get(bytes);
return new String(bytes);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment