代码示例
1.server端
package com.learning.block;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;
import static com.learning.bytebuffer.ByteBufferUtil.debugRead;
@Slf4j
public class Server {
public static void main(String[] args) throws IOException {
ByteBuffer byteBuffer = ByteBuffer.allocate(16);
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(8080));
List<SocketChannel> socketChannelList = new ArrayList<>();
while(true){
log.info("connecting...");
SocketChannel socketChannel = serverSocketChannel.accept();
log.info("connected...{}", socketChannel);
socketChannelList.add(socketChannel);
for(SocketChannel channel : socketChannelList){
log.info("before read...{}", channel);
channel.read(byteBuffer);
byteBuffer.flip();
debugRead(byteBuffer);
byteBuffer.clear();
log.debug("after read...{}", channel);
}
}
}
}
2.client端
package com.learning.block;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
public class Client {
public static void main(String[] args) throws IOException {
SocketChannel sc = SocketChannel.open();
sc.connect(new InetSocketAddress("localhost", 8080));
System.out.println("waiting...");
}