ServerSocketChannel 实现文件服务器
2013年08月22日
⁄ 综合
⁄ 共 1067字 ⁄ 字号
小 中 大
-
package test.io;
-
-
import java.nio.channels.*;
-
import java.nio.charset.*;
-
import java.net.*;
-
import java.io.*;
-
import java.util.*;
-
import java.nio.*;
-
-
public class FileServer {
-
private int port = 8050;
-
-
private ServerSocketChannel serverSocketChannel;
-
-
private Charset charset = Charset.forName("GBK");
-
-
private Selector selector = null;
-
-
public FileServer() throws IOException {
-
selector = Selector.open();
-
serverSocketChannel = ServerSocketChannel.open();
-
serverSocketChannel.socket().setReuseAddress(true);
-
serverSocketChannel.socket().bind(new InetSocketAddress(port));
-
System.out.println("服务器启动");
-
}
-
-
-
public ByteBuffer encode(String str) {
-
return charset.encode(str);
-
}
-
-
-
public String decode(ByteBuffer bb) {
-
return charset.decode(bb).toString();
-
}
-
-
-
public void service() throws IOException {
-
serverSocketChannel.configureBlocking(false);
-
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
-