package NIOTEST;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set; public class NIOServer {
public static void main(String[] args) throws IOException, InterruptedException {
Selector selector = Selector.open(); ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
InetSocketAddress address = new InetSocketAddress(InetAddress.getLocalHost(), 8080);
serverSocketChannel.socket().bind(address);
serverSocketChannel.configureBlocking(false);
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); while (true) {
if (selector.select() > 0) {
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> it = selectionKeys.iterator();
while (it.hasNext()) {
SelectionKey selectionKey = it.next();
if (selectionKey.isAcceptable()) {
serverSocketChannel = (ServerSocketChannel)selectionKey.channel();
SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
System.out.println("Connected: " + socketChannel.socket().getRemoteSocketAddress());
} else if (selectionKey.isReadable()) {
SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (socketChannel.read(buffer) > 0) {
buffer.flip();
byte[] dis = new byte[buffer.limit()];
buffer.get(dis);
System.out.println("当前线程="+Thread.currentThread().getId()+"--"+new String(dis));
}
} it.remove();
}
} Thread.sleep(100);
}
}
}

客户端

package NIOTEST;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;
public class NIOClient {
public static void main(String[] args) throws IOException {
SocketChannel socketChannel = SocketChannel.open();
InetSocketAddress address = new InetSocketAddress(InetAddress.getLocalHost(), 8080);
socketChannel.socket().connect(address); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true) {
try {
buffer.clear();
String time = sdf.format(new Date());
buffer.put(time.getBytes());
buffer.flip();
socketChannel.write(buffer);
Thread.sleep(5000);
} catch (Exception e) {
System.out.println("Connection Close");
break;
}
}
}
}

利用NIO的Selector处理服务器-客户端模型的更多相关文章

  1. 基于TCP协议 I/O多路转接(select) 的高性能回显服务器客户端模型

    服务端代码: myselect.c #include <stdio.h> #include <netinet/in.h> #include <arpa/inet.h> ...

  2. Nio使用Selector客户端与服务器的通信

    使用NIO的一个最大优势就是客户端于服务器自己的不再是阻塞式的,也就意味着服务器无需通过为每个客户端的链接而开启一个线程.而是通过一个叫Selector的轮循器来不断的检测那个Channel有消息处理 ...

  3. 利用NIO建立Socket服务器

    传统的Java 的IO,利用Socket建立服务器,接收客户端连接,一般都是为每一个连接建立一个线程,如果连接数巨大,那么服务器开销也将巨大..NIO的原理,可以参照图:http://new.51ct ...

  4. java的nio之:java的nio的服务器实现模型

    [nio服务端序列图]

  5. Java IO 与 NIO 服务器&客户端通信小栗子

    本篇包含了入门小栗子以及一些问题的思考 BIO package com.demo.bio; import java.io.*; import java.net.ServerSocket; import ...

  6. NIO【同步非阻塞io模型】关于 NIO socket 的详细总结【Java客户端+Java服务端 + 业务层】【可以客户端间发消息】

    1.前言 以前使用 websocket来实现双向通信,如今深入了解了 NIO 同步非阻塞io模型 , 优势是 处理效率很高,吞吐量巨大,能很快处理大文件,不仅可以 做 文件io操作, 还可以做sock ...

  7. Linux 下 简单客户端服务器通讯模型(TCP)

    原文:Linux 下 简单客户端服务器通讯模型(TCP) 服务器端:server.c #include<stdio.h> #include<stdlib.h> #include ...

  8. 系统编程-网络-tcp客户端服务器编程模型(续)、连接断开、获取连接状态场景

    相关博文: 系统编程-网络-tcp客户端服务器编程模型.socket.htons.inet_ntop等各API详解.使用telnet测试基本服务器功能 接着该上篇博文,咱们继续,首先,为了内容的完整性 ...

  9. NIO组件 Selector(选择器)

    简介 使用Selector(选择器), 可以使用一个线程处理多个客户端连接. Selector 能够检测多个注册的通道上是否有事件发生(多个Channel以事件的方式可以注册到同一个Selector) ...

随机推荐

  1. #请用索引取出下面list的指定元素:

    #!/usr/bin/python # -*- coding: utf-8 -*- L = [ ['Apple', 'Google', 'Microsoft'], ['Java', 'Python', ...

  2. AtCoder - 3962 Sequence Growing Hard

    Problem Statement Find the number of the possible tuples of sequences (A0,A1,…,AN) that satisfy all ...

  3. [BZOJ4398]福慧双修/[BZOJ2407]探险

    题目大意: 给定一个$n(n\leq40000)$个点$m(m\leq100000)$条边的有向图,求从$1$出发回到$1$的不经过重复结点的最短路. 思路: 首先Dijkstra求出从1出发到每个结 ...

  4. NOIP 2017 赛后反思 [补档]

    首先写一下比赛的情况: D1: T1: 之前做过类似的题目, 因而知道大致的结论, 迅速完成. T2: 貌似直接模拟就可以了, 涉及到字符串信息提取, 比较麻烦, 因而想放到最后做. T3: 非常简洁 ...

  5. 集合框架(中):Map

    Map接口: Map提供了一种映射关系,其中的元素就是以键值对(key-value)的形式存储的,能够实现根据key快速查找value Map中的键值对以Entry类型的对象实例形式存在 键(key值 ...

  6. rs485

    rs485 编辑 智能仪表是随着80年代初单片机技术的成熟而发展起来的,现在世界仪表市场基本被智能仪表所垄断.究其原因就是企业信息化的需要,企业在仪表选型时其中的一个必要条件就是要具有联网通信接口.最 ...

  7. Android反编译调试源码

    Android反编译调试源码 1. 反编译得到源码 直接在windows 命令行下输入命令java -jar apktool_2.0.0.jar d -d 小米运动_1.4.641_1058.apk ...

  8. [置顶] kubernetes资源类型--ingress

    Ingress在K8S1.1之前还没有. 概念 Ingress是一种HTTP方式的路由转发机制,为K8S服务配置HTTP负载均衡器,通常会将服务暴露给K8S群集外的客户端. Ingress是一个允许入 ...

  9. C++完美实现Singleton模式[转]

    Singleton模式是常用的设计模式之一,但是要实现一个真正实用的设计模式却也不是件容易的事情.1. 标准的实现class Singleton{public: static Singleton * ...

  10. gzip解压和压缩

    我发现网上很少有这样完整例子,加上英文有不好,走了好多弯路.我现在把从网上找到例子帖出来,可以解压HTTP gzip的 #include <stdlib.h> #include <s ...