现在的位置: 首页 > 综合 > 正文

ServerSocketChannel 实现文件服务器

2013年08月22日 ⁄ 综合 ⁄ 共 1067字 ⁄ 字号 评论关闭
[java] view
plain
copy

  1. package test.io;  
  2.   
  3. import java.nio.channels.*;  
  4. import java.nio.charset.*;  
  5. import java.net.*;  
  6. import java.io.*;  
  7. import java.util.*;  
  8. import java.nio.*;  
  9.   
  10. public class FileServer {  
  11.   private int port = 8050;  
  12.   
  13.   private ServerSocketChannel serverSocketChannel;  
  14.   
  15.   private Charset charset = Charset.forName("GBK");  
  16.   
  17.   private Selector selector = null;  
  18.   
  19.   public FileServer() throws IOException {  
  20.     selector = Selector.open();  
  21.     serverSocketChannel = ServerSocketChannel.open();  
  22.     serverSocketChannel.socket().setReuseAddress(true);  
  23.     serverSocketChannel.socket().bind(new InetSocketAddress(port));  
  24.     System.out.println("服务器启动");  
  25.   }  
  26.   
  27.   /* 编码过程 */  
  28.   public ByteBuffer encode(String str) {  
  29.     return charset.encode(str);  
  30.   }  
  31.   
  32.   /* 解码过程 */  
  33.   public String decode(ByteBuffer bb) {  
  34.     return charset.decode(bb).toString();  
  35.   }  
  36.   
  37.   /* 服务器服务方法 */  
  38.   public void service() throws IOException {  
  39.     serverSocketChannel.configureBlocking(false);  
  40.     serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);  

抱歉!评论已关闭.