JAVA 网络传输10张图片
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
public class Server {
public static void main(String[] args) throws IOException {
int sd = 0;
File file = new File("D:/tp/");
File[] listFiles = file.listFiles();
ServerSocketChannel ssc = ServerSocketChannel.open().bind(new InetSocketAddress(8888));
ssc.configureBlocking(false);
Selector selector = Selector.open();
ssc.register(selector, SelectionKey.OP_ACCEPT);
while (selector.select()>0 ) {
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
SelectionKey skey = iterator.next();
if (skey.isAcceptable()) {
SocketChannel socketChannel = ssc.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
}
if (skey.isReadable()) {
SocketChannel socketChannel2 =(SocketChannel) skey.channel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024 * 1024);
sd++;
socketChannel2.read(byteBuffer);
FileChannel fileChannel = new FileOutputStream("d:/tp2/sd.jpg").getChannel();
byteBuffer.flip();
fileChannel.write(byteBuffer);
byteBuffer.clear();
}
iterator.remove();
}
if (sd ==1)
{
break;
}
}
}
}