- 浏览: 16406 次
- 性别:
- 来自: 北京
最新评论
-
xcc313:
解决我的问题了,
Hibernate的Antlr.jar与weblogic.jar冲突:ClassNotFoundException: org.hibernate.hql.ast -
maozilee:
NIO开发对于很少开发c/s架构的人来说 太困难了,,所以mi ...
Java socket 开源框架MINA (一) -
maozilee:
还有一个经典的图的。。
Java socket 及 开源框架MINA(二) -
maozilee:
mina开发c/s架构的程序简单多了
Java socket 开源框架MINA(三)
nio socket 及其开源框架MINA学习总结(一)
1:传统socket:阻塞式通信
每建立一个Socket连接时,同时创建一个新线程对该Socket进行单独通信(采用阻塞的方式通信)。这种方式具有很高的响应速度,并且控制起来也很简单,在连接数较少的时候非常有效,但是如果对每一个连接都产生一个线程的无疑是对系统资源的一种浪费,如果连接数较多将会出现资源不足的情况。
example:
2.nio:非阻塞通讯模式
2.1NIO 设计背后的基石:反应器模式,用于事件多路分离和分派的体系结构模式。
反应器模式的核心功能如下:
将事件多路分用
将事件分派到各自相应的事件处理程序
NIO 的非阻塞 I/O 机制是围绕 选择器和 通道构建的。Channel 类表示服务器和客户机之间的一种通信机制。Selector 类是 Channel 的多路复用器。 Selector 类将传入客户机请求多路分用并将它们分派到各自的请求处理程序。
通道(Channel 类):表示服务器和客户机之间的一种通信机制。
选择器(Selector类):是 Channel 的多路复用器。
Selector 类将传入的客户机请求多路分用并将它们分派到各自的请求处理程序。简单的来说:NIO是一个基于事件的IO架构,最基本的思想就是:有事件我通知你,你再去做你的事情.而且NIO的主线程只有一个,不像传统的模型,需要多个线程以应对客户端请求,也减轻了JVM的工作量。
当Channel注册至Selector以后,经典的调用方法如下: nio中取得事件通知,就是在selector的select事件中完成的。在selector事件时有一个线程向操作系统询问,selector中注册的Channel&&SelectionKey的键值对的各种事件是否有发生,如果有则添加到selector的selectedKeys属性Set中去,并返回本次有多少个感兴趣的事情发生。如果发现这个值>0,表示有事件发生,马上迭代selectedKeys中的SelectionKey,
根据Key中的表示的事件,来做相应的处理。实际上,这段说明表明了异步socket的核心,即异步socket不过是将多个socket的调度(或者还有他们的线程调度)全部交给操作系统自己去完成,异步的核心Selector,不过是将这些调度收集、分发而已。
2.2 nio example:
server code:
1:传统socket:阻塞式通信
每建立一个Socket连接时,同时创建一个新线程对该Socket进行单独通信(采用阻塞的方式通信)。这种方式具有很高的响应速度,并且控制起来也很简单,在连接数较少的时候非常有效,但是如果对每一个连接都产生一个线程的无疑是对系统资源的一种浪费,如果连接数较多将会出现资源不足的情况。
example:
server code: public class MultiUserServer extends Thread { private Socket client; public MultiUserServer(Socket c) { this.client = c; } public void run() { try { BufferedReader in = new BufferedReader(new InputStreamReader(client .getInputStream())); PrintWriter out = new PrintWriter(client.getOutputStream()); // Mutil User but can't parallel while (true) { String str = in.readLine(); System.out.println(str); SocketLog.debug("receive message: " + str); out.println("has receive...."); out.flush(); if (str.equals("end")) break; } client.close(); } catch (IOException ex) { } } public static void main(String[] args) throws IOException { int port = 5678; if (args.length > 0) port = Integer.parseInt(args[0]); ServerSocket server = new ServerSocket(port); SocketLog.debug("the server socket application is created!"); while (true) { // transfer location change Single User or Multi User MultiUserServer mu = new MultiUserServer(server.accept()); mu.start(); } } } client code: public class Client { static Socket server; public static void main(String[] args) throws Exception { //set socket proxy. String proxyHost = "192.16.24.12"; String proxyPort = "1080"; System.getProperties().put("socksProxySet","true"); System.getProperties().put("socksProxyHost",proxyHost); System.getProperties().put("socksProxyPort",proxyPort); String host = "12.201.29.10"; int port = 10086; if (args.length > 1) { host = args[0]; port = Integer.parseInt(args[1]); } System.out.println("connetioning:" + host + ":" + port); server = new Socket(host, port); BufferedReader in = new BufferedReader(new InputStreamReader(server .getInputStream())); PrintWriter out = new PrintWriter(server.getOutputStream()); BufferedReader wt = new BufferedReader(new InputStreamReader(System.in)); while (true) { String str = wt.readLine(); out.println(str); out.flush(); if (str.equals("end")) { break; } System.out.println(in.readLine()); } server.close(); } }
2.nio:非阻塞通讯模式
2.1NIO 设计背后的基石:反应器模式,用于事件多路分离和分派的体系结构模式。
反应器模式的核心功能如下:
将事件多路分用
将事件分派到各自相应的事件处理程序
NIO 的非阻塞 I/O 机制是围绕 选择器和 通道构建的。Channel 类表示服务器和客户机之间的一种通信机制。Selector 类是 Channel 的多路复用器。 Selector 类将传入客户机请求多路分用并将它们分派到各自的请求处理程序。
通道(Channel 类):表示服务器和客户机之间的一种通信机制。
选择器(Selector类):是 Channel 的多路复用器。
Selector 类将传入的客户机请求多路分用并将它们分派到各自的请求处理程序。简单的来说:NIO是一个基于事件的IO架构,最基本的思想就是:有事件我通知你,你再去做你的事情.而且NIO的主线程只有一个,不像传统的模型,需要多个线程以应对客户端请求,也减轻了JVM的工作量。
当Channel注册至Selector以后,经典的调用方法如下: nio中取得事件通知,就是在selector的select事件中完成的。在selector事件时有一个线程向操作系统询问,selector中注册的Channel&&SelectionKey的键值对的各种事件是否有发生,如果有则添加到selector的selectedKeys属性Set中去,并返回本次有多少个感兴趣的事情发生。如果发现这个值>0,表示有事件发生,马上迭代selectedKeys中的SelectionKey,
根据Key中的表示的事件,来做相应的处理。实际上,这段说明表明了异步socket的核心,即异步socket不过是将多个socket的调度(或者还有他们的线程调度)全部交给操作系统自己去完成,异步的核心Selector,不过是将这些调度收集、分发而已。
while (somecondition) { int n = selector.select(TIMEOUT); if (n == 0) continue; for (Iterator iter = selector.selectedKeys().iterator(); iter .hasNext();) { if (key.isAcceptable()) doAcceptable(key); if (key.isConnectable()) doConnectable(key); if (key.isValid() && key.isReadable()) doReadable(key); if (key.isValid() && key.isWritable()) doWritable(key); iter.remove(); } }
2.2 nio example:
server code:
public class NonBlockingServer { public Selector sel = null; public ServerSocketChannel server = null; public SocketChannel socket = null; public int port = 4900; String result = null; public NonBlockingServer() { System.out.println("Inside default ctor"); } public NonBlockingServer(int port) { System.out.println("Inside the other ctor"); this.port = port; } public void initializeOperations() throws IOException,UnknownHostException { System.out.println("Inside initialization"); sel = Selector.open(); server = ServerSocketChannel.open(); server.configureBlocking(false); InetAddress ia = InetAddress.getLocalHost(); InetSocketAddress isa = new InetSocketAddress(ia,port); server.socket().bind(isa); } public void startServer() throws IOException { System.out.println("Inside startserver"); initializeOperations(); System.out.println("Abt to block on select()"); SelectionKey acceptKey = server.register(sel, SelectionKey.OP_ACCEPT ); while (acceptKey.selector().select() > 0 ) { Set readyKeys = sel.selectedKeys(); Iterator it = readyKeys.iterator(); while (it.hasNext()) { SelectionKey key = (SelectionKey)it.next(); it.remove(); if (key.isAcceptable()) { System.out.println("Key is Acceptable"); ServerSocketChannel ssc = (ServerSocketChannel) key.channel(); socket = (SocketChannel) ssc.accept(); socket.configureBlocking(false); SelectionKey another = socket.register(sel,SelectionKey.OP_READ|SelectionKey.OP_WRITE); } if (key.isReadable()) { System.out.println("Key is readable"); String ret = readMessage(key); if (ret.length() > 0) { writeMessage(socket,ret); } } if (key.isWritable()) { System.out.println("THe key is writable"); String ret = readMessage(key); socket = (SocketChannel)key.channel(); if (result.length() > 0 ) { writeMessage(socket,ret); } } } } } public void writeMessage(SocketChannel socket,String ret) { System.out.println("Inside the loop"); if (ret.equals("quit") || ret.equals("shutdown")) { return; } try { String s = "This is context from server!-----------------------------------------"; Charset set = Charset.forName("us-ascii"); CharsetDecoder dec = set.newDecoder(); CharBuffer charBuf = dec.decode(ByteBuffer.wrap(s.getBytes())); System.out.println(charBuf.toString()); int nBytes = socket.write(ByteBuffer.wrap((charBuf.toString()).getBytes())); System.out.println("nBytes = "+nBytes); result = null; } catch(Exception e) { e.printStackTrace(); } } public String readMessage(SelectionKey key) { int nBytes = 0; socket = (SocketChannel)key.channel(); ByteBuffer buf = ByteBuffer.allocate(1024); try { nBytes = socket.read(buf); buf.flip(); Charset charset = Charset.forName("us-ascii"); CharsetDecoder decoder = charset.newDecoder(); CharBuffer charBuffer = decoder.decode(buf); result = charBuffer.toString(); } catch(IOException e) { e.printStackTrace(); } return result; } public static void main(String args[]) { NonBlockingServer nb; if (args.length < 1) { nb = new NonBlockingServer(); } else { int port = Integer.parseInt(args[0]); nb = new NonBlockingServer(port); } try { nb.startServer(); System.out.println("the nonBlocking server is started!"); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } } } client code: public class Client { public SocketChannel client = null; public InetSocketAddress isa = null; public RecvThread rt = null; private String host; private int port; public Client(String host, int port) { this.host = host; this.port = port; } public void makeConnection() { String proxyHost = "192.168.24.22"; String proxyPort = "1080"; System.getProperties().put("socksProxySet", "true"); System.getProperties().put("socksProxyHost", proxyHost); System.getProperties().put("socksProxyPort", proxyPort); int result = 0; try { client = SocketChannel.open(); isa = new InetSocketAddress(host, port); client.connect(isa); client.configureBlocking(false); receiveMessage(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } long begin = System.currentTimeMillis(); sendMessage(); long end = System.currentTimeMillis(); long userTime = end - begin; System.out.println("use tiem: " + userTime); try { interruptThread(); client.close(); System.exit(0); } catch (IOException e) { e.printStackTrace(); } } public int sendMessage() { System.out.println("Inside SendMessage"); String msg = null; ByteBuffer bytebuf; int nBytes = 0; try { msg = "It's message from client!"; System.out.println("msg is "+msg); bytebuf = ByteBuffer.wrap(msg.getBytes()); for (int i = 0; i < 1000; i++) { nBytes = client.write(bytebuf); System.out.println(i + " finished"); } interruptThread(); try { Thread.sleep(5000); } catch (Exception e) { e.printStackTrace(); } client.close(); return -1; } catch (IOException e) { e.printStackTrace(); } return nBytes; } public void receiveMessage() { rt = new RecvThread("Receive THread", client); rt.start(); } public void interruptThread() { rt.val = false; } public static void main(String args[]) { if (args.length < 2) { System.err.println("You should put 2 args: host,port"); } else { String host = args[0]; int port = Integer.parseInt(args[1]); Client cl = new Client(host, port); cl.makeConnection(); } BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String msg; } public class RecvThread extends Thread { public SocketChannel sc = null; public boolean val = true; public RecvThread(String str, SocketChannel client) { super(str); sc = client; } public void run() { int nBytes = 0; ByteBuffer buf = ByteBuffer.allocate(2048); try { while (val) { while ((nBytes = nBytes = client.read(buf)) > 0) { buf.flip(); Charset charset = Charset.forName("us-ascii"); CharsetDecoder decoder = charset.newDecoder(); CharBuffer charBuffer = decoder.decode(buf); String result = charBuffer.toString(); System.out.println("the server return: " + result); buf.flip(); } } } catch (IOException e) { e.printStackTrace(); }
发表评论
-
Spring中使用classpath加载配置文件浅析
2011-09-14 14:21 704在应用Spring的工程中,使用class path的方式加载 ... -
Dom4j遍历解析XML测试
2011-05-17 13:04 764环境: Dom4j-1.6.1 Dom4j解析需要XML需 ... -
为已有的web project项目加入maven支持,并使用myeclipse的插件
2011-04-15 17:32 1645项目还是之前的项目,现在我要在原有项目中加入maven支持,但 ... -
Java socket 开源框架MINA(三)
2011-01-19 13:41 1309下面的这个简单的example演示client和server传 ... -
Java socket 及 开源框架MINA(二)
2011-01-19 13:38 16523:Socket网络框架 MINA MINA是一个网络应用框架 ... -
quartz报错java.lang.NoSuchMethodError: org.apache.commons.collections.SetUtils.ord
2010-10-08 11:32 1440出现Caused by: java.lang.NoSuchMe ... -
QQ在线咨询代码
2010-08-17 08:25 770<a target=blank href=tencent ... -
Hibernate的Antlr.jar与weblogic.jar冲突:ClassNotFoundException: org.hibernate.hql.ast
2010-08-04 08:52 1736Hibernate使用的文法分析器是antlr,WebLogi ...
相关推荐
常见NIO开源框架(MINA、xSocket)学习 基于io包的阻塞式socket通信代码简单,在连接数很少的情况下是一个不错的选择。不过实际应用中一个socket服务器采用传统的阻塞式socket方式通信可能会是一场灾难,一路...
niosocket及其开源框架MINA学习总结收集.pdf
java客户端socket与mina服务端通信,保持长连接
Mina2.0框架:客户端Demo,服务器端Demo,根目录下有整理的《Mina2.0学习笔记》
高性能Java网络框架 MINA
java mina 通讯框架
高性能Java网络框架 MINA.7z
是跟手机进行推送功能的时候整理的工具,有长连接也有socket短连接,代码能直接运行,jar包和代码都有 直接放到项目里可以用,有mian测试方法
mina测试框架 mina测试框架 mina测试框架
java mina框架
Apache MINA 是一个开发高性能和高可伸缩性网络应用程序的网络应用框架。它提供了一个抽象的事件驱动的异步 API,可以使用 TCP/IP、UDP/IP、串口和虚拟机内部的管道等传输方式。Apache MINA 可以作为开发网络应用...
java mina 服务端,socket客服端传信息,客服端上传消息
详细介绍mina框架的各个组成部分、服务器端的开发、客户端开发。并根据本人在工程项目中使用的代码,详细讲解了服务器端是客户端实现。实现了json格式的通信、以及文件的上传于下载等功能。图文并茂,以开发者的角度...
基于Java的米娜框架,报告对使用基于Java、websocket协议的网页聊天室的过程和技术做了详细的叙述首先,对现有网页进行了分析与评价。首先, 启动后台服务器,然后连接站点,客户端在pc端输入网站或者在手机端扫...
Mina开源框架 心跳机制详解
基于java的开发源码-mina高性能Java网络框架.zip 基于java的开发源码-mina高性能Java网络框架.zip 基于java的开发源码-mina高性能Java网络框架.zip 基于java的开发源码-mina高性能Java网络框架.zip 基于java的开发...
JAVA mina 框架源码,非常好。。。。。。。。。
mina socket 的一个简单示例!
通过Mina与Socket实现通信,其包含客户端与服务端的实现代码
基于Java的高性能Java网络框架 MINA.zip