(1)第一种解决方案(等待连接时和等待数据时不阻塞)
- public class Server {
- public static void main(String[] args) throws InterruptedException {
- ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
- try {
- //Java为非阻塞设置的类
- ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
- serverSocketChannel.bind(new InetSocketAddress(8080));
- //设置为非阻塞
- serverSocketChannel.configureBlocking(false);
- while(true) {
- SocketChannel socketChannel = serverSocketChannel.accept();
- if(socketChannel==null) {
- //表示没人连接
- System.out.println("正在等待客户端请求连接...");
- Thread.sleep(5000);
- }else {
- System.out.println("当前接收到客户端请求连接...");
- }
- if(socketChannel!=null) {
- //设置为非阻塞
- socketChannel.configureBlocking(false);
- byteBuffer.flip();//切换模式 写-->读
- int effective = socketChannel.read(byteBuffer);
- if(effective!=0) {
- String content = Charset.forName("utf-8").decode(byteBuffer).toString();
- System.out.println(content);
- }else {
- System.out.println("当前未收到客户端消息");
- }
- }
- }
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
运行结果
(编辑:威海站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|