版权声明:本文为博主原创文章,未经博主同意不得转载。 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. 本地主机访问远程linux系统服务器上的jupyter notebook

    1,机器情况:服务器 centos python环境已经配置好了,在虚拟环境下安装了anaconda 并且在里面安装了jupyter notebook 2,主机是 windows     ipytho ...

  2. Codeforces 1192B 全dfs序 + 线段树

    题意:给你一颗树,每次会修改一条边的边权,问修改之后的树的直径是多少? 思路:来源于:https://www.cnblogs.com/TinyWong/p/11260601.html 得到树的全序df ...

  3. GetExtendedTcpTable

    https://blog.csdn.net/sky101010ws/article/details/55511501 AdjustTokenPrivileges function Library Ad ...

  4. mpvue实现微信小程序(欢迎踩坑)

    最近刚使用mpvue完成了微信小程序的开发,写点东西,做个记录. 首先依旧是两个传送门: 微信小程序文档:[https://developers.weixin.qq.com/miniprogram/d ...

  5. js reduce用法

    let books = [ 0, {bookName:"python",price:10,count:1}, {bookName:"Ruby",count:2, ...

  6. OC端代码

    ViewController.m #import "ViewController.h"#import <Flutter/Flutter.h>#include " ...

  7. JMeter 分布式调度压测部署

    我们遇到jmeter被假死死了,这里有2个原因,一是jmeter原本是java写的,heap受硬件限制需要调优,二是单机无法分解超大并发比如100万+并发压测,因此,我们分二部走,首先我们需要进行jm ...

  8. 表单修饰符 number、trim、lazy

    number修饰符 <input type="number" v-model.number="age"> 结论:age 类型则为number,非字符 ...

  9. 002-序列化装换JSON&XML概述

    一.概述 https://github.com/bjlhx15/java-serializer java-serializer 序列化项目 serialize-json-lib:json-lib框架 ...

  10. FCKEditor添加字体

    默认情况下,FCKEditor在进行文本编辑时,无法使用中文字体.自个摸索了下:打开 fckconfig.js 文件 找到第154行(应该是),会发现:FCKConfig.FontNames = 'A ...