java 基础之--nio 网络编程
在传统的Java 网络编程中,对于客户端的每次连接,对于服务器来说,都要创建一个新的线程与客户端进行通讯,这种频繁的线程的创建,对于服务器来说,是一种巨大的损耗,在Java 1.4 引入Java nio 引入了 selector channel buffer 对此操作进行重新的定义:
服务端:
package com.java.baseknowledge.net; import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Set; public class NioService {
//store userMap
public static Map<Integer,SocketChannel> userMap =new HashMap<>();
public static void main(String[] args) throws Exception { //selector object
Selector selector =Selector.open();
//serversocketchannel object is listening client accept
ServerSocketChannel serverSocket =ServerSocketChannel.open();
//Adjusts this channel's blocking mode.
serverSocket.configureBlocking(false); serverSocket.bind(new InetSocketAddress(9099));
//在selector中register channel
serverSocket.register(selector, SelectionKey.OP_ACCEPT); while(true) {
//block method event listening,this method is perform when event is touch;
selector.select();
//get selection-key set
Set<SelectionKey> selectedKeys = selector.selectedKeys(); selectedKeys.forEach((keys->{
//judge selectionkey mode
if(keys.isAcceptable()) {
try {
ServerSocketChannel channel = (ServerSocketChannel)keys.channel();
//obtain socketchannel
SocketChannel accept = channel.accept();
accept.configureBlocking(false);
//regist selector,listening read event
accept.register(selector, SelectionKey.OP_READ);
userMap.put(new Random().nextInt()*new Random().nextInt(), accept); }
catch(Exception e ) {
e.printStackTrace();
}
} else if(keys.isReadable()) {
//obtain socketchannel
try {
SocketChannel channel = (SocketChannel)keys.channel();
System.out.println(channel);
ByteBuffer by = ByteBuffer.allocate(2048);
channel.read(by); userMap.forEach((k,v)->{ by.rewind();
if(v!=channel) {
try {
v.write(by);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}); }
catch(Exception e) {} }
selectedKeys.clear(); })); } } }
客户端:
package com.java.baseknowledge.net; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
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.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; /**
* chat client
* @author Administrator
*
*/
public class JavaNioClient { public static void main(String[] args) throws Exception { //建立Selector
Selector selector =Selector.open();
SocketChannel socketChannel=SocketChannel.open();
//设置非阻塞
socketChannel.configureBlocking(false); socketChannel.register(selector, SelectionKey.OP_CONNECT); socketChannel.connect(new InetSocketAddress("127.0.0.1", 9099)); while(true) {
selector.select(); Set<SelectionKey> setionkey =selector.selectedKeys(); for(SelectionKey kk :setionkey) {
if(kk.isConnectable()) {
//从selectionkey 获取socketChannel
SocketChannel socket=(SocketChannel)kk.channel();
//手动建立连接
if(socket.isConnectionPending()) {
socket.finishConnect();
//写数据
ByteBuffer byteB = ByteBuffer.allocate(1024);
byteB.put((System.currentTimeMillis()+"连接ok").getBytes());
byteB.flip();
socket.write(byteB);
//jdk1.5 线程池
ExecutorService exe =Executors.newSingleThreadExecutor(Executors.defaultThreadFactory()); exe.submit(new Thread() { @Override
public void run() {
while(true) {
String msg=null;
byteB.clear();
//标准键盘输入
BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
try {
msg =br.readLine();
ByteBuffer bytec = ByteBuffer.allocate(1024);
bytec.put(msg.getBytes());
bytec.flip();
socket.write(bytec);
} catch (IOException e) { e.printStackTrace();
}
}
}
});
} socket.register(selector, SelectionKey.OP_READ);
}
else if(kk.isReadable()) { //从selectionkey 获取socketChannel
SocketChannel socket=(SocketChannel)kk.channel();
ByteBuffer by =ByteBuffer.allocate(1024);
int a=socket.read(by);
//if(a>0) {
String receive =new String(by.array());
System.out.println(receive);
//}
} setionkey.clear();
} } } }
java 基础之--nio 网络编程的更多相关文章
- JAVA基础知识之网络编程——-网络基础(Java的http get和post请求,多线程下载)
本文主要介绍java.net下为网络编程提供的一些基础包,InetAddress代表一个IP协议对象,可以用来获取IP地址,Host name之类的信息.URL和URLConnect可以用来访问web ...
- Java基础教程:网络编程
Java基础教程:网络编程 基础 Socket与ServerSocket Socket又称"套接字",网络上的两个程序通过一个双向的通信连接实现数据的交换,这个连接的一端称为一个s ...
- java基础学习总结——网络编程
一.网络基础概念 首先理清一个概念:网络编程 != 网站编程,网络编程现在一般称为TCP/IP编程.
- Java 基础高级2 网络编程
1.协议的概念:通信双方事先约定好的通信规则 2七层网络通信协议:应用成,表示层,会话层,传输层,网络层,数据链路层 3.TCP/IP协议:点对点通信,三层握手,安全有保证 4.UDP协议;广播协议, ...
- JAVA基础知识之网络编程——-网络通信模型(IO模型)
<Unix网络编程:卷1>中介绍了5中I/O模型,JAVA作为运行在宿主机上的程序,底层也遵循这5中I/O模型规则.这5中I/O模型分别是: 阻塞式IO 非阻塞式IO I/O复用 信号驱动 ...
- 【java基础学习】网络编程
网络编程 InetAddress tcp udp
- 【Java基础总结】网络编程
网络编程 InetAddress tcp udp
- JAVA基础知识之网络编程——-基于NIO的非阻塞Socket通信
阻塞IO与非阻塞IO 通常情况下的Socket都是阻塞式的, 程序的输入输出都会让当前线程进入阻塞状态, 因此服务器需要为每一个客户端都创建一个线程. 从JAVA1.4开始引入了NIO API, NI ...
- JAVA基础知识之网络编程——-基于UDP协议的通信例子
UDP是一种不可靠的协议,它在通信两端各建立一个socket,这两个socket不会建立持久的通信连接,只会单方面向对方发送数据,不检查发送结果. java中基于UDP协议的通信使用DatagramS ...
随机推荐
- jquery接触初级-----juqery选择器实例
jquery 选择器用于触发事件,可以少写很多js代码,一般来说,基本的特效功能都能够完成 这里列举一个简单的jquery写的例子: 要求:有两种情况: 1.产品最初状态显示简约形式的品牌,即显示部分 ...
- Linux命令之lsof
1.lsof简介 lsof(list open files)是一个列出当前系统打开文件的工具.在linux环境下,任何事物都以文件的形式存在,通过文件不仅仅可以访问常规数据,还可以访问网络连接和硬件. ...
- jeecg使用小结
1.上传word模板时报“java.lang.UnsatisfiedLinkError: no jacob-1.17-M2-x64 in java.library.path”异常 原因:jdk下没有找 ...
- Linux下查看与修改mtu值
MTU:通信术语 最大传输单元(Maximum Transmission Unit)是指一种通信协议的某一层上面所能通过的最大数据包大小(以字节为单位). 我们在使用互联网时进行的各种网络操作,都是通 ...
- C语言中插入汇编nop指令
工作过程中,有的时候需要打桩cycle,想在C语言中插入nop指令,可以采取的方法是 头文件中加入#inlude <stdio.h> 定义一个内联函数,然后调用这个函数,不过得测一下平台调 ...
- SPSS-判别分析
判别分析 判别分析是一种有效的对个案进行分类分析的方法.和聚类分析不同的是,判别分析时组别的特征已知. 定义:判别分析先根据已知类别的事物的性质,利用某种技术建立函数式,然后对未知类别的新事物进 行判 ...
- 安装 protoc 的各种坑
首先下载 protoc 2.6.1 https://github.com/google/protobuf/releases/download/v2.6.1/protobuf-2.6.1.tar.g ...
- MFC笔记1
1.在对话框文档中定义两个定时器,每间隔5秒弹出一个消息框提示“定时器1”,每隔5秒弹出一个消息框提示“定时器2” UINT ID_TIMER1 = 1 , ID_TIMER2 = 2; //设置 ...
- ./configure: error: the HTTP rewrite module requires the PCRE library解决
./configure: error: the HTTP rewrite module requires the PCRE library解决 有时候,我们需要单独安装nginx,来处理大量的下载 ...
- Template literals
[Template literals] Template literals are string literals allowing embedded expressions. You can use ...