以下方法为阻塞模式(单线程) 只能干一件事。
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.netty.c1.ByteBufferUtil.debugRead;
@Slf4j(topic = "c.Server")
public class Server {
public static void main(String[] args) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(16);
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.bind(new InetSocketAddress(8080));
List<SocketChannel> channels = new ArrayList<>();
while(true) {
log.debug("connection...");
SocketChannel sc = ssc.accept();
log.debug("connected...{}",sc);
channels.add(sc);
for (SocketChannel channel : channels) {
log.debug("before read...{}",channel);
channel.read(buffer);
buffer.flip();
debugRead(buffer);
buffer.clear();
log.debug("after read...{}",channel);
}
}
}
}
以下方法为非阻塞模式(单线程)
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.netty.c1.ByteBufferUtil.debugRead;
@Slf4j(topic = "c.Server")
public class Server {
public static void main(String[] args) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(16);
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking(false);
ssc.bind(new InetSocketAddress(8080));
List<SocketChannel> channels = new ArrayList<>();
while(true) {
SocketChannel sc = ssc.accept();
if(sc != null){
log.debug("connected...{}",sc);
sc.configureBlocking(false);
channels.add(sc);
}
for (SocketChannel channel : channels) {
int read = channel.read(buffer);
if(read > 0) {
buffer.flip();
debugRead(buffer);
buffer.clear();
log.debug("after read...{}", channel);
}
}
}
}
}
|