java NIO socket 通信实例
版权声明:本文为博主原创文章,未经博主同意不得转载。 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 通信实例的更多相关文章
- Flex通信-与Java实现Socket通信实例
Flex通信-与Java实现Socket通信实例 转自:http://blessht.iteye.com/blog/1136888 博客分类: Flex 环境准备 [服务器端] JDK1.6,“ja ...
- Java NIO Socket编程实例
各I/O模型优缺点 BIO通信模型 BIO主要的问题在于每当有一个新的客户端请求接入时,服务端必须创建一个新的线程处理新接入的客户端链路,一个线程只能处理一个客户端连接 线程池I/O编程 假如所有可用 ...
- Java nio socket与as3 socket(粘包解码)连接的应用实例
对Java nio socket与as3 socket连接的简单应用 <ignore_js_op>Java nio socket与as3 socket连接的应用实例.rar (9.61 K ...
- Java Socket 通信实例 - 转载
基于Tcp协议的简单Socket通信实例(JAVA) 好久没写博客了,前段时间忙于做项目,耽误了些时间,今天开始继续写起~ 今天来讲下关于Socket通信的简单应用,关于什么是Socket以及一些 ...
- Linux下简单的socket通信实例
Linux下简单的socket通信实例 If you spend too much time thinking about a thing, you’ll never get it done. —Br ...
- 网络协议栈学习(一)socket通信实例
网络协议栈学习(一)socket通信实例 该实例摘自<linux网络编程>(宋敬彬,孙海滨等著). 例子分为服务器端和客户端,客户端连接服务器后从标准输入读取输入的字符串,发送给服务器:服 ...
- (8)Linux(客户端)和Windows(服务端)下socket通信实例
Linux(客户端)和Windows(服务端)下socket通信实例: (1)首先是Windows做客户端,Linux做服务端的程序 Windows Client端 #include <st ...
- java nio实现非阻塞Socket通信实例
服务器 package com.java.xiong.Net17; import java.io.IOException; import java.net.InetSocketAddress; imp ...
- Java NIO Socket 非阻塞通信
相对于非阻塞通信的复杂性,通常客户端并不需要使用非阻塞通信以提高性能,故这里只有服务端使用非阻塞通信方式实现 客户端: package com.test.client; import java.io. ...
随机推荐
- linux安装 inotify
[root@rsync-client-inotify ~]# yum install make gcc gcc-c++ [root@rsync-client-inotify ~]# wget http ...
- lvm分区创建和扩容
shell> fdisk /dev/xvdb #### 选择磁盘 Command (m for help): m #### 帮助 Command action a toggle a bootab ...
- less: 变量
在Less中声明变量方式是使用@符号 @test_width: 300px; .box { width: @test_width; height: @test_width; background-co ...
- Sublime-Text macOS 编译运行armadillo
{ "cmd" : ["g++ -std=c++14 -Wall -larmadillo -framework Accelerate ${file_name} -o ${ ...
- hdu 5963:朋友
刚看到这题时感觉是树上博弈,然后我开始用一维的数据找规律.发现在一维的树上,如果把各边的值合在一起当成一个二进制数,那么,ans只与奇偶性有关,于是,我提出了一个比较大胆的假设:若连接在root上的所 ...
- 02 IDEA创创建第一个maven工程
导入坐标
- Python3解leetcode First Bad Version
问题描述: You are a product manager and currently leading a team to develop a new product. Unfortunately ...
- php strcspn()函数 语法
php strcspn()函数 语法 作用:输出在字符串中找到某字符之前查找的字符数.直线电机参数 语法:strcspn(string,char,start,length) 参数: 参数 描述 str ...
- php长连接和短连接的使用场景
短连接 连接->传输数据->关闭连接 比如HTTP是无状态的的短链接,浏览器和服务器每进行一次HTTP操作,就建立一次连接,但任务结束就中断连接. 具体就是 浏览器client发起并建立T ...
- windows下使用Ant编译Android项目
1. 安装ant,配置环境变量 2. 执行命令: android update project -p 项目路径 例:android update project -p D:\project\UI_de ...