今天先介绍NioSocket的基本用法,实际使用一般会采用多线程,后面会介绍多线程的处理方法。

从jdk1.4开始,java增加了新的io模式--nio(new IO),nio在底层采用了新的处理方式,极大地提高了IO效率。我们使用的Socket也属于IO的一种,nio提供了相应的工具:ServerSocketChanner和SocketChannel,它们分别对应ServerSocket和Socket。(不了解java socket可以百度下)

NioSocket包括三个重要的概念:Buffer(类似于送快递中的货物)、Channel(类似于送快递中的送货车)和Selector(类似于送快递中转站的分拣员)。原来的Socket类似于一个人送快递,没有形成产业链。

下面来看下代码:

服务端

package com.test;

import java.io.IOException;

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.nio.charset.Charset;

import java.util.Iterator;

public class NIOServer {

public static void main(String[] args) throws Exception {

//创建ServerSocketChannel,监听8080端口

ServerSocketChannel ssc =  ServerSocketChannel.open();

ssc.socket().bind(new InetSocketAddress(8080));

//设置为非阻塞模式

ssc.configureBlocking(false);

//为ServerSocketChannel注册选择器

Selector selector = Selector.open();

/**

* 这里有四种SelectionKey分别表示接受请求操作、链接操作、读操作和写操作

* SelectionKey.OP_ACCEPT

* SelectionKey.OP_CONNECT

* SelectionKey.OP_READ

* SelectionKey.OP_WRITE

*/

ssc.register(selector, SelectionKey.OP_ACCEPT);

//创建处理器

Handler handler = new Handler(1024);//handler的创建在下面静态的内部类中

while(true){

//等待请求,每次等待阻塞3s,超过3s后线程继续向下运动,如果传入0或者不传入参数将一直阻塞

if(selector.select(3000) == 0){

System.out.println("等待请求超时....");

continue;

}

System.out.println("处理请求......");

//获取待处理的SelectionKey

Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();

while(keyIter.hasNext()){

SelectionKey key = keyIter.next();

try {

//接收到链接请求时

if(key.isAcceptable()){

handler.handAccept(key);//改变Selector为读操作

}

//读数据

if(key.isReadable()){

handler.handlerRead(key);

}

} catch (Exception e) {

keyIter.remove();

continue;

}

//处理完成后,从待处理的SelectionKey迭代器中移除当前所使用的key

keyIter.remove();

}

}

}

public static class Handler{

private int bufferSize = 1024;

private String localCharset = "UTF-8";

public Handler() {}

public Handler(int bufferSize) {

this(bufferSize,null);

}

public Handler(String localCharset) {

this(-1,localCharset);

}

public Handler(int bufferSize, String localCharset) {

if(bufferSize>0){

this.bufferSize = bufferSize;

}

if(localCharset != null){

this.localCharset = localCharset;

}

}

public void handAccept(SelectionKey key) throws IOException {

SocketChannel sc = ((ServerSocketChannel)key.channel()).accept();

sc.configureBlocking(false);

sc.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(bufferSize));//改变Selector为读操作

}

public void handlerRead(SelectionKey key) throws IOException {

//获取channel

SocketChannel sc = (SocketChannel) key.channel();

//获取channel并重置

ByteBuffer buffer = (ByteBuffer) key.attachment();

buffer.clear();

//没有读到内容则关闭

if(sc.read(buffer)==-1){

sc.close();

}else{

//将buffer转成读状态

buffer.flip();

//将buffer中接收到的值按localCharset格式编码后保存到receivedString

String receivedString = Charset.forName(localCharset).newDecoder().decode(buffer).toString();

System.out.println("received from client: " + receivedString);

//返回数据给客户端

String sendString = "received data: " + receivedString;

buffer = ByteBuffer.wrap(sendString.getBytes(localCharset));

sc.write(buffer);

//关闭socket

sc.close();

}

}

}

}

161111、NioSocket的用法(new IO)的更多相关文章

  1. Java中的Socket的用法

                                   Java中的Socket的用法 Java中的Socket分为普通的Socket和NioSocket. 普通Socket的用法 Java中的 ...

  2. 第一篇 网站基础知识 第4章 Java中Socket的用法

    第4章 Java中Socket的用法 4.1 普通Socket的用法 Java中的网络通信是通过Socket实现的,Socket分为ServetSocket和Socket两大类,ServetSocke ...

  3. Java中的Socket用法

    转发链接:https://www.cnblogs.com/zhanglei93/p/6217384.html (1)Java中的Socket用法 Java中的Socket分为普通的Socket和Nio ...

  4. 利用socket.io实现消息实时推送

    最近在写的项目中存在着社交模块,需要实现这样的一个功能:当发生了用户被点赞.评论.关注等操作时,需要由服务器向用户实时地推送一条消息.最终完成的项目地址为:socket-message-push,这里 ...

  5. 高级Java工程师必备 ----- 深入分析 Java IO (三)

    概述 Java IO即Java 输入输出系统.不管我们编写何种应用,都难免和各种输入输出相关的媒介打交道,其实和媒介进行IO的过程是十分复杂的,这要考虑的因素特别多,比如我们要考虑和哪种媒介进行IO( ...

  6. Java之io nio aio 的区别

    这个问题最近面试总是遇到,作为一个只会写流水代码的程序员,一脸懵逼.看了网上的解释,看的还是很模糊,说下我对这个的理解. 先引出一个话题,两个大水缸,一个空一个满,让你把一个缸里面的水弄到另一个里面. ...

  7. 转: 从Mysql某一表中随机读取n条数据的SQL查询语句

    若要在i ≤ R ≤ j 这个范围得到一个随机整数R ,需要用到表达式 FLOOR(i + RAND() * (j – i + 1)).例如, 若要在7 到 12 的范围(包括7和12)内得到一个随机 ...

  8. .net(C#)操作文件的几种方法汇总

    .net(C#)操作文件的几种方法汇总 System.IO命名空间下类的用法:在System.IO名称空间中包含了用于文件输入输出的主要类.File:实用类,提供许多静态方法,用于移动.复制和删除文件 ...

  9. 【MySQL性能优化】改进MySQL Order By Rand()的低效率

    <a href="http://click.aliyun.com/m/9153/">点击查看原文</a> 正 文:   最近由于需要研究了一下MYSQL的随 ...

随机推荐

  1. 为什么一个object_id在dba_objects中为什么查不到记录?

    SQL> drop table test purge;SQL> create table test (id int,comments CLOB); SQL> select INDEX ...

  2. DMV to track the temp file usage for SQLServer

    There are three DMVs you can use to track tempdb usage: sys.dm_db_task_space_usagesys.dm_db_session_ ...

  3. each的详解

    首先我还是先观察w3c讲解: 先写一段代码,如图: 定义:each() 方法规定为每个匹配元素规定运行的函数. 提示:返回 false 可用于及早停止循环.(我在代码中加了return false,发 ...

  4. vmware虚拟机三种网络模式详解_转

    原文来自http://note.youdao.com/share/web/file.html?id=236896997b6ffbaa8e0d92eacd13abbf&type=note 由于L ...

  5. Vue.2.0.5-Class 与 Style 绑定

    Class 与 Style 绑定 数据绑定一个常见需求是操作元素的 class 列表和它的内联样式.因为它们都是属性 ,我们可以用v-bind 处理它们:只需要计算出表达式最终的字符串.不过,字符串拼 ...

  6. UIPageControl

    UIPageControl 1.    numberOfPages // 设置有多少页默认为0 // 2) 设置页数 [pageControl setNumberOfPages:kImageCount ...

  7. CentOS安装Git

    准备安装Gityum install curl-devel expat-devel gettext-devel openssl-devel zlib-devel perl-devel #下载git-1 ...

  8. electron "Cannot find module 'dialog'", source: module.js (336)"

    打算用electron的dialog api 谁知道, 按官方api http://electron.atom.io/docs/v0.33.0/api/dialog/ https://github.c ...

  9. PostgreSQL Monitor pg_view

    PostgreSQL Monitor pg_view https://github.com/zalando/pg_view Requirements Linux 2.6, python 2.6, ps ...

  10. pg_rewind 介绍

    pg_rewind—使一个PostgreSQL数据目录与另一个数据目录(该目录从第一个PostgreSQL数据目录创建而来)一致. 描述 pg_rewind是一个在集群的时间线参数偏离之后,用于使一个 ...