版权声明:本文为博主原创文章,未经博主同意不得转载。 https://blog.csdn.net/zhuyijian135757/article/details/37672151

java Nio 通信与Bio通信主要不同点:

1.Nio中的单个channel就可以支持读操作也能够支持写操作,而bio中读操作要用inputstream,写操作要outputstream.

2.nio 採用byteBuffer 作为内存缓存区,向channel里写或者度操作,bio基本是用byte[]

3.nio採用 selector组件轮询读取就绪channel

服务端demo代码:

package com.my.socket3;
import java.io.ByteArrayOutputStream;
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.util.Iterator;
import java.util.Set; import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream; public class ServerTest { public static void main(String[] args) throws Exception {
server();
} public static void server(){
ServerSocketChannel channel=null;
try{ Selector selector=Selector.open();
channel=ServerSocketChannel.open();
channel.configureBlocking(false);
channel.socket().setReuseAddress(true);
channel.bind(new InetSocketAddress(8020));
channel.register(selector, SelectionKey.OP_ACCEPT,new Integer(1)); while(true){
if(selector.select()>0){
Set<SelectionKey> sets=selector.selectedKeys();
Iterator<SelectionKey> keys=sets.iterator();
while(keys.hasNext()){
SelectionKey key=keys.next();
keys.remove(); if(key.isAcceptable()){
key.attach(new Integer(1));
SocketChannel schannel=((ServerSocketChannel) key.channel()).accept();
schannel.configureBlocking(false);
schannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
} if(key.isReadable()){
SocketChannel schannel=(SocketChannel) key.channel();
ByteBuffer buf=ByteBuffer.allocate(1024);
ByteOutputStream output=new ByteOutputStream();
int len=0;
while((len=schannel.read(buf))!=0){
buf.flip();
byte by[]=new byte[buf.remaining()];
buf.get(by);
output.write(by);
buf.clear();
}
String str=new String(output.getBytes());
key.attach(str);
} if(key.isWritable()){ Object object=key.attachment();
String attach=object!=null ? "server replay: "+object.toString() : "server replay: ";
SocketChannel schannel=(SocketChannel) key.channel();
schannel.write(ByteBuffer.wrap(attach.getBytes()));
}
}
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(channel!=null){
try {
channel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} }
}

客户端demo代码

package com.my.socket3;
import java.io.ByteArrayOutputStream;
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.SocketChannel;
import java.util.Iterator;
import java.util.Set; public class ClientTest { public static void main(String[] args) throws Exception {
client();
} public static void client() {
SocketChannel channel=null;
try { Selector selector=Selector.open();
channel = SocketChannel.open();
channel.configureBlocking(false);
channel.connect(new InetSocketAddress(8020));
channel.register(selector, SelectionKey.OP_CONNECT); while(true){
if(selector.select()>0){ Iterator<SelectionKey> set=selector.selectedKeys().iterator();
while(set.hasNext()){
SelectionKey key=set.next();
set.remove(); SocketChannel ch=(SocketChannel) key.channel();
if(key.isConnectable()){
ch.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE,new Integer(1));
ch.finishConnect();
} if(key.isReadable()){
key.attach(new Integer(1));
ByteArrayOutputStream output=new ByteArrayOutputStream();
ByteBuffer buffer=ByteBuffer.allocate(1024);
int len=0;
while((len=ch.read(buffer))!=0){
buffer.flip();
byte by[]=new byte[buffer.remaining()];
buffer.get(by);
output.write(by);
buffer.clear();
}
System.out.println(new String(output.toByteArray()));
output.close();
} if(key.isWritable()){
key.attach(new Integer(1));
ch.write(ByteBuffer.wrap((("client say:hi")).getBytes()));
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
channel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} static class ClientRunnable implements Runnable{ private SocketChannel ch; private ClientRunnable(SocketChannel ch){
this.ch=ch;
} @Override
public void run() {
try {
while(true){
ch.write(ByteBuffer.wrap((("client say:hi")).getBytes()));
Thread.sleep(5000);
}
} catch (Exception e) {
e.printStackTrace();
try {
ch.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
} }

跑demo时遇到的问题

1.客户端须要进行 ch.finishiCnonnect()操作,否则两边都堵塞着

2.读channel中的bytebuffer时, while((len=ch.read(buffer))!=0) 推断不要写成while((len=ch.read(buffer))!=-1) 

假设SocketChannel被设置为非堵塞,则它的read操作可能返回三个值:
1) 大于0,表示读取到了字节数。
2) 等于0。没有读取到消息,可能TCP处于Keep-Alive状态,接收到的是TCP握手消息。
3) -1,连接已经被对方合法关闭。

java NIO socket 通信实例的更多相关文章

  1. Flex通信-与Java实现Socket通信实例

    Flex通信-与Java实现Socket通信实例  转自:http://blessht.iteye.com/blog/1136888 博客分类: Flex 环境准备 [服务器端] JDK1.6,“ja ...

  2. Java NIO Socket编程实例

    各I/O模型优缺点 BIO通信模型 BIO主要的问题在于每当有一个新的客户端请求接入时,服务端必须创建一个新的线程处理新接入的客户端链路,一个线程只能处理一个客户端连接 线程池I/O编程 假如所有可用 ...

  3. Java nio socket与as3 socket(粘包解码)连接的应用实例

    对Java nio socket与as3 socket连接的简单应用 <ignore_js_op>Java nio socket与as3 socket连接的应用实例.rar (9.61 K ...

  4. Java Socket 通信实例 - 转载

    基于Tcp协议的简单Socket通信实例(JAVA)   好久没写博客了,前段时间忙于做项目,耽误了些时间,今天开始继续写起~ 今天来讲下关于Socket通信的简单应用,关于什么是Socket以及一些 ...

  5. Linux下简单的socket通信实例

    Linux下简单的socket通信实例 If you spend too much time thinking about a thing, you’ll never get it done. —Br ...

  6. 网络协议栈学习(一)socket通信实例

    网络协议栈学习(一)socket通信实例 该实例摘自<linux网络编程>(宋敬彬,孙海滨等著). 例子分为服务器端和客户端,客户端连接服务器后从标准输入读取输入的字符串,发送给服务器:服 ...

  7. (8)Linux(客户端)和Windows(服务端)下socket通信实例

    Linux(客户端)和Windows(服务端)下socket通信实例: (1)首先是Windows做客户端,Linux做服务端的程序 Windows   Client端 #include <st ...

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

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

  9. Java NIO Socket 非阻塞通信

    相对于非阻塞通信的复杂性,通常客户端并不需要使用非阻塞通信以提高性能,故这里只有服务端使用非阻塞通信方式实现 客户端: package com.test.client; import java.io. ...

随机推荐

  1. Manjaro美化 配置教程

    Manjaro Linux的美化 切换源 sudo vi /etc/pacman.conf 加入arch源 [archlinuxcn] SigLevel = Optional TrustedOnly ...

  2. nginx http正向代理简单配置及systemd 配置

    #user nobody; worker_processes 1; #error_log logs/error.log; #error_log logs/error.log notice; #erro ...

  3. ps:图像格式的选择

    从上面点阵与矢量两者的对比中,似乎矢量格式有优势,那为什么不都使用矢量格式呢? 这是因为矢量图像是基于线段的.因此它不适合记录色彩较为复杂的图像.如下图, 如果使用点阵方式来记录,只要按照顺序扫描并记 ...

  4. 多线程AQS

    参考: AQS原理分析 https://blog.csdn.net/javazejian/article/details/75043422 重入读写锁原理分析 https://blog.csdn.ne ...

  5. JS基础入门篇(三)— for循环,取余,取整。

    1.for循环 1.for的基本简介 作用: 根据一定的条件,重复地执行一行或多行代码 语法: for( 初始化 ; 判断条件 ; 条件改变 ){ 代码块 } 2.for循环的执行顺序 <bod ...

  6. LeetCode--045--跳跃游戏II(java)

    给定一个非负整数数组,你最初位于数组的第一个位置. 数组中的每个元素代表你在该位置可以跳跃的最大长度. 你的目标是使用最少的跳跃次数到达数组的最后一个位置. 示例: 输入: [2,3,1,1,4] 输 ...

  7. Vue项目【饿了么App】mock数据【data.json】

    1.前后端分离式开发,约定好数据字段接口! 2.前端mock静态数据,开发完毕后,与后端进行数据联调! 3.vue.config.js 配置 devServer const appData = req ...

  8. 阿里云Serverless应用引擎(SAE)3大核心优势全解析

    软件发展到今,企业业务系统日趋复杂,开发一个业务系统需要掌握和关注的知识点越来越多.除实现业务逻辑本身,还需考虑很多非业务的基础技术系统:如分布式cache和队列.基础服务能力集成.容量规划.弹性伸缩 ...

  9. OC + RAC (九) 过滤

    // 跳跃 : 如下,skip传入2 跳过前面两个值 // 实际用处: 在实际开发中比如 后台返回的数据前面几个没用,我们想跳跃过去,便可以用skip - (void)skip { RACSubjec ...

  10. 黑苹果 MacOS 10.15 Catalina安装教程

    10.15 Catalina 桌面 一.准备工作 一个8G以上的U盘(有的U盘标的是8G,实际只有7.X,实际容量小于7.5G的会失败) MacOS镜像.TransMac(刻录工具).DiskGeni ...