Created
November 22, 2013 10:45
-
-
Save daeyun/7597989 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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