以下方法为阻塞模式(单线程)
只能干一件事。
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)); Listchannels = 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)); Listchannels = new ArrayList<>(); // 有一个缺点:没有连接请求时,也会不断循环。 // 没有数据可读时,也会不断循环。 while(true) { //log.debug("connection..."); // 建立与客户端的连接 SocketChannel sc = ssc.accept(); // 非阻塞,线程还会继续运行。如果没有建立连接,sc是null if(sc != null){ log.debug("connected...{}",sc); sc.configureBlocking(false); channels.add(sc); } // 接受客户端发送的数据 for (SocketChannel channel : channels) { //log.debug("before read...{}",channel); int read = channel.read(buffer); // 非阻塞,线程仍然继续运行。如果没有读到数据,read返回0 if(read > 0) { buffer.flip(); debugRead(buffer); buffer.clear(); log.debug("after read...{}", channel); } } } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)