服务端
public class NetServer {
public static void main(String[] args) {
ByteBuffer byteBuffer = ByteBuffer.allocate(16);
try (ServerSocketChannel ssc = ServerSocketChannel.open()) {
ssc.bind(new InetSocketAddress(8082));
ArrayList<SocketChannel> scs = new ArrayList<>();
while (true) {
System.out.println("before Connection....");
SocketChannel sc = ssc.accept();
scs.add(sc);
for (SocketChannel socketChannel : scs) {
System.out.println("connecting");
socketChannel.read(byteBuffer);
System.out.println("reading...");
byteBuffer.flip();
String s = StandardCharsets.UTF_8.decode(byteBuffer).toString();
byteBuffer.clear();
System.out.println(s);
}
}
} catch (IOException e) {
}
}
}
客户端
public class NetClient {
public static void main(String[] args) {
try (SocketChannel sc = SocketChannel.open()) {
System.out.println("waiting");
sc.connect(new InetSocketAddress("localhost",8082));
System.out.println("spreading...");
} catch (IOException e) {
}
}
}
String与缓存区字符转换
//String转换为ByteBuffer
ByteBuffer hello = StandardCharsets.UTF_8.encode("hello");
//ByteBuffer转换为String
String s = StandardCharsets.UTF_8.decode(hello).toString();