java channel学习

来源:互联网 发布:笔记本触摸屏软件 编辑:程序博客网 时间:2024/06/05 09:30

Channel类似于传统的流对象,但与传统的流对象有两个主要区别:

1、Channel可以直接将指定文件的部分或全部直接映射成Buffer。

2、程序不能直接访问Channel中的数据,包括读、写入都不行,Channel只能与Buffer进行交互。也就是说,如果要从Channel中取得数据,必须先用Buffer从Channel中取出一些数据,然后让程序从Buffer中取出这些数据;如果要将程序中的数据写入Channel,一样先让程序将谁放入Buffer中,程序再将Buffer里的数据写入Channel中。

 

创建serversocket对象

ServerSocketChannel ssc = ServerSocketChannel.open();ServerSocket serverSocket = ssc.socket(); // Listen on port 1234serverSocket.bind(new InetSocketAddress(1234));

 

阻塞和非阻塞

 

传统的serversocket阻塞模式:

public class ServerSocketApp {public static void main(String[] args) throws Exception {ServerSocket ss = new ServerSocket(8989);ss.accept();System.out.println(1);}}

    运行这个程序 为什么没有输出1 ??? 

    因为ServerSocket  是阻塞模式的 ,什么是阻塞,就是在没有任何连接之前,accept方法一直在那里阻塞着,直到有connection来继续往下执行,所以在运行程序的时候,并没输出1,若要输出  telnet一下就可以了

 

nio中的 非阻塞:

public static void main(String[] args) throws Exception {ServerSocketChannel ssc = ServerSocketChannel.open();ServerSocket ss = ssc.socket();ss.bind(new InetSocketAddress(8989));// set no blockingssc.configureBlocking(false);ssc.accept();System.out.println(1);}

 

例子: 

package channel;import java.io.IOException;import java.net.InetAddress;import java.net.InetSocketAddress;import java.net.Socket;import java.net.SocketAddress;import java.net.UnknownHostException;import java.nio.channels.ServerSocketChannel;import java.nio.channels.SocketChannel;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class NioTest {private ExecutorService es = null;private static int port = 8083;private ServerSocketChannel ssc = null;public static final int POOL_MULTIPLE = 4;// 线程池中的工作线程的数量public NioTest() throws IOException {// Runtime.getRuntime().availableProcessors()) Returns the number of// processors available to the Java virtual machine.es = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * POOL_MULTIPLE);// 每个处理器处理POOL_MULTIPLE个线程ssc = ServerSocketChannel.open();// 静态函数返回一个ServerSocketChannel实例ssc.socket().setReuseAddress(true);// 使得关闭服务器后再次启动服务器程序可以顺利绑定相同的端口ssc.socket().bind(new InetSocketAddress(port));// 绑定端口es.execute(new Runnable() {public void run() {try {SocketChannel s = ssc.accept();// s.socket()返回socket对象,利用socket对象就可以进行流的读取和写入了。System.out.println(s.socket().getInetAddress());s.close();} catch (IOException e) {e.printStackTrace();}}});// 创建客户端连接到服务器端。es.execute(new Runnable() {public void run() {try {// Socket s = new Socket("localhost", port);// s.close();SocketChannel s = SocketChannel.open();InetAddress i = InetAddress.getLocalHost();System.out.println("client InetAddress : " + i);s.connect(new InetSocketAddress(i, port));} catch (UnknownHostException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}});es.shutdown();// 关闭线程池。}public static void main(String[] args) throws IOException {new NioTest();}}

 

原创粉丝点击