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. ...
随机推荐
- Sql Server 出现此数据库没有有效所有者问题
在新建数据库或附加数据库后,想添加关系表,结果出现下面的错误: 此数据库没有有效所有者,因此无法安装数据库关系图支持对象.若要继续,请首先使用“数据库属性”对话框的“文件”页或ALTER AUTHO ...
- C# 开发 Windows 服务 使用Log4net 组件 不能生成日志文件
使用VS2012开发Windows服务,需要使用Log4net日志组件记录业务情况,但是始终生成不了日志文件. /// <summary> /// 入口方法 /// </summar ...
- 学Python的第四天
第四天啦,今天依旧代码少的啃树皮.... 但是作业留的有了幼儿园的水准!!!让小编我看到了希望.... #!/usr/bin/env python # -*- coding:utf8 -*- impo ...
- Ansible笔记(1)---基本概念
一.ansible的作用以及工作结构 1.1.ansible简介: ansible是新出现的自动化运维工具,基于Python开发,集合了众多运维工具(puppet.cfengine.chef.func ...
- bzoj5118 Fib数列2 二次剩余+矩阵快速幂
题目传送门 https://lydsy.com/JudgeOnline/problem.php?id=5118 题解 这个题一看就是不可做的样子. 求斐波那契数列的第 \(n\) 项,\(n \leq ...
- Pyhton---基础---递归
2019-05-21 ------------------------------------------- 一. #类似于栈的先进后出模式def digui(num): print(num) ...
- python——解释型语言
编程语言分三大类 : 低级语言 . 汇编语言 . 高级语言. 现代计算机都是基于 图灵机模型 制造的. 因此计算机的内部只能接受二进制数据.而用二进制代码 0 1 描述的指令叫 ...
- android 6.0适配(总结)
6.0的适配主要是权限: 权限的分组: 普通权限:也就是正常权限,是对手机的一些正常操作,对用户的隐私没有太大影响的权限,比如手机的震动,网络访问,蓝牙等权限,这些权限会在应用被安装的时候默认授予,用 ...
- Linux负载均衡软件LVS
linux下的开源负载均衡软件LVS的安装.配置和使用.LVS是一个中国人创建和开发的开放源码项目,利用LVS可以构建高可用.高可靠的负载均衡集群,因此,利用Linux+LVS不但可以假设高性能的负载 ...
- 170814关于Cookie的知识点
1.会话控制 Http协议 Http协议两个缺陷: 1.HTTP协议是纯文本的 2.HTTP协议是无状态的 服务器不能简单的通过HTTP协议来区分多次请求是否发自同一个用户 虽然通过H ...