server:

 /**
* 选择器服务端
* Created by ascend on 2017/6/9 9:30.
*/
public class SelectorServer {
// public final static String REMOTE_IP = "192.168.0.44";
public final static String REMOTE_IP = "127.0.0.1";
public final static int PORT = 17531;
private static ByteBuffer bb = ByteBuffer.allocate(1024);
private static ServerSocketChannel ssc;
private static boolean closed = false; public static void main(String[] args) throws IOException {
//先确定端口号
int port = PORT;
if (args != null && args.length > 0) {
port = Integer.parseInt(args[0]);
}
//打开一个ServerSocketChannel
ssc = ServerSocketChannel.open();
//获取ServerSocketChannel绑定的Socket
ServerSocket ss = ssc.socket();
//设置ServerSocket监听的端口
ss.bind(new InetSocketAddress(port));
//设置ServerSocketChannel为非阻塞模式
ssc.configureBlocking(false);
//打开一个选择器
Selector selector = Selector.open();
//将ServerSocketChannel注册到选择器上去并监听accept事件
SelectionKey selectionKey = ssc.register(selector, SelectionKey.OP_ACCEPT); while (!closed) {
//这里会发生阻塞,等待就绪的通道,但在每次select()方法调用之间,只有一个通道就绪了。
int n = selector.select();
//没有就绪的通道则什么也不做
if (n == 0) {
continue;
}
//获取SelectionKeys上已经就绪的集合
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); //遍历每一个Key
while (iterator.hasNext()) {
SelectionKey sk = iterator.next();
//通道上是否有可接受的连接
if (sk.isAcceptable()) {
ServerSocketChannel sscTmp = (ServerSocketChannel) sk.channel();
SocketChannel sc = sscTmp.accept(); // accept()方法会一直阻塞到有新连接到达。
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
} else if (sk.isReadable()) { //通道上是否有数据可读
try {
readDataFromSocket(sk);
} catch (IOException e) {
sk.cancel();
continue;
}
}
if (sk.isWritable()) { //测试写入数据,若写入失败在会自动取消注册该键
try {
writeDataToSocket(sk);
} catch (IOException e) {
sk.cancel();
continue;
}
}
//必须在处理完通道时自己移除。下次该通道变成就绪时,Selector会再次将其放入已选择键集中。
iterator.remove();
}//. end of while } } /**
* 发送测试数据包,若失败则认为该socket失效
*
* @param sk SelectionKey
* @throws IOException IOException
*/
private static void writeDataToSocket(SelectionKey sk) throws IOException {
SocketChannel sc = (SocketChannel) sk.channel();
bb.clear();
String str = "server data";
bb.put(str.getBytes());
while (bb.hasRemaining()) {
sc.write(bb);
}
} /**
* 从通道中读取数据
*
* @param sk SelectionKey
* @throws IOException IOException
*/
private static void readDataFromSocket(SelectionKey sk) throws IOException {
SocketChannel sc = (SocketChannel) sk.channel();
bb.clear();
List<Byte> list = new ArrayList<>();
while (sc.read(bb) > 0) {
bb.flip();
while (bb.hasRemaining()) {
list.add(bb.get());
}
bb.clear();
}
byte[] bytes = new byte[list.size()];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = list.get(i);
}
String s = (new String(bytes)).trim();
if (!s.isEmpty()) {
if ("exit".equals(s)){
ssc.close();
closed = true;
}
System.out.println("服务器收到:" + s);
}
} }

client:

 /**
*
* Created by ascend on 2017/6/13 10:36.
*/
public class Client { @org.junit.Test
public void test(){
Socket socket = new Socket();
try {
socket.connect(new InetSocketAddress(SelectorServer.REMOTE_IP,SelectorServer.PORT));
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.write("exit".getBytes());
out.flush();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
} public static void main(String[] args) {
new Thread(new ClientThread()).start();
} public void checkStatus(String input){
if ("exit".equals(input.trim())) {
System.out.println("系统即将退出,bye~~");
System.exit(0);
}
} } class ClientThread implements Runnable {
private SocketChannel sc;
private boolean isConnected = false;
Client client = new Client(); public ClientThread(){
try {
sc = SocketChannel.open();
sc.configureBlocking(false);
sc.connect(new InetSocketAddress(SelectorServer.REMOTE_IP,SelectorServer.PORT));
while (!sc.finishConnect()) {
System.out.println("同" + SelectorServer.REMOTE_IP + "的连接正在建立,请稍等!");
Thread.sleep(10);
}
System.out.println("连接已建立,待写入内容至指定ip+端口!时间为" + System.currentTimeMillis());
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
} @Override
public void run() {
try {
while (true){
Scanner scanner = new Scanner(System.in);
System.out.print("请输入要发送的内容:");
String writeStr = scanner.nextLine();
client.checkStatus(writeStr);
ByteBuffer bb = ByteBuffer.allocate(writeStr.length());
bb.put(writeStr.getBytes());
bb.flip(); // 写缓冲区的数据之前一定要先反转(flip)
while (bb.hasRemaining()){
sc.write(bb);
}
bb.clear();
}
} catch (IOException e) {
e.printStackTrace();
if (Objects.nonNull(sc)) {
try {
sc.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}finally {
if (Objects.nonNull(sc)) {
try {
sc.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}

java nio--采用Selector实现Socket通信的更多相关文章

  1. java nio实现非阻塞Socket通信实例

    服务器 package com.java.xiong.Net17; import java.io.IOException; import java.net.InetSocketAddress; imp ...

  2. JAVA基础知识之网络编程——-基于NIO的非阻塞Socket通信

    阻塞IO与非阻塞IO 通常情况下的Socket都是阻塞式的, 程序的输入输出都会让当前线程进入阻塞状态, 因此服务器需要为每一个客户端都创建一个线程. 从JAVA1.4开始引入了NIO API, NI ...

  3. 170407、java基于nio工作方式的socket通信

    客户端代码: /** * */ package com.bobohe.nio; import java.io.BufferedReader; import java.io.IOException; i ...

  4. Java NIO类库Selector机制解析(上)

    一.  前言 自从J2SE 1.4版本以来,JDK发布了全新的I/O类库,简称NIO,其不但引入了全新的高效的I/O机制,同时,也引入了多路复用的异步模式.NIO的包中主要包含了这样几种抽象数据类型: ...

  5. Java NIO类库Selector机制解析--转

    一.  前言 自从J2SE 1.4版本以来,JDK发布了全新的I/O类库,简称NIO,其不但引入了全新的高效的I/O机制,同时,也引入了多路复用的异步模式.NIO的包中主要包含了这样几种抽象数据类型: ...

  6. Java与C之间的socket通信

    最近正在开发一个基于指纹的音乐检索应用,算法部分已经完成,所以尝试做一个Android App.Android与服务器通信通常采用HTTP通信方式和Socket通信方式.由于对web服务器编程了解较少 ...

  7. Java NIO之Selector(选择器)

    历史回顾: Java NIO 概览 Java NIO 之 Buffer(缓冲区) Java NIO 之 Channel(通道) 其他高赞文章: 面试中关于Redis的问题看这篇就够了 一文轻松搞懂re ...

  8. java scoket Blocking 阻塞IO socket通信四

    记住NIO在jdk1.7版本之前是同步非阻塞的,以前的inputsream是同步阻塞的,上面学习完成了Buffer现在我们来学习channel channel书双向的,以前阻塞的io的inputstr ...

  9. Java NIO类库Selector机制解析(下)

    五.  迷惑不解 : 为什么要自己消耗资源? 令人不解的是为什么我们的Java的New I/O要设计成这个样子?如果说老的I/O不能多路复用,如下图所示,要开N多的线程去挨个侦听每一个Channel ...

随机推荐

  1. hdu4292 Food 最大流模板题

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4292 题意:水和饮料,建图跑最大流模板. 我用的是学长的模板,最然我还没有仔细理解,不过这都不重要直接 ...

  2. Extjs grid禁用头部点击三角下拉菜单

    表格头部的三角在点击的时候禁止出现下拉菜单,给每一列添加属性menuDisabled:true xtype:'grid', enableColumnResize:false, columns:[ {t ...

  3. LOJ#120. 持久化序列(FHQ Treap)

    题面 传送门 题解 可持久化\(Treap\)搞一搞 //minamoto #include<bits/stdc++.h> #define R register #define inlin ...

  4. JavaScript--History 对象

    history对象记录了用户曾经浏览过的页面(URL),并可以实现浏览器前进与后退相似导航的功能. 注意:从窗口被打开的那一刻开始记录,每个浏览器窗口.每个标签页乃至每个框架,都有自己的history ...

  5. 转载使用 ContentObsever 拦截短信,获取短信内容

    在一些应用上,比如手机银行,QQ,微信等,很多时候我们都需要通过发送验证码到手机上,然后把验证码填上去,然后才能成功地继续去做下面一步事情. 而如果每次我们都要离开当前界面,然后去查收短信,记住验证码 ...

  6. random模块思维导图

  7. headroom.js使用

    为页面顶部多留些空间.在不需要页头时将其隐藏 需要添加的css代码 .headroom { transition: transform 200ms linear; } .headroom--pinne ...

  8. LN : leetcode 217 Contains Duplicate

    lc 217 Contains Duplicate 217 Contains Duplicate Given an array of integers, find if the array conta ...

  9. mysql的简单优化【简单易学】

    1.选取最适用的字段属性: 表字段尽量设小,不要给数据库增加没必要的空间:如:值为'01'.'02',给char(2)即可: 2.使用连接(JOIN)来代替子查询(Sub-Queries): 使用jo ...

  10. 61配置nanopim1plus的HDMI为1080p输出

    61配置nanopim1plus的HDMI为1080p输出 大文实验室/大文哥 壹捌陆捌零陆捌捌陆捌贰 21504965 AT qq.com 完成时间:2018/4/4 10:21 版本:V1.1 开 ...