java.nio 今天刚做个了nio的小demo 发现传输速度特别慢......如何解决。。那位高手指点下。只是传输byte【】过去
迷茫中我也是昨天刚接触这个。所以....高手指点指点下

解决方案 »

  1.   


    package x.t;import java.io.File;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.MappedByteBuffer;
    import java.nio.channels.FileChannel;
    import java.nio.channels.SocketChannel;import org.apache.log4j.Logger;import x.MsgHeader; 
    public class Client { private Logger logger = Logger.getLogger(Client.class); private SocketChannel schannel; private FileChannel fchannel; private RandomAccessFile raf; public Client(String host, int port) throws IOException {
    InetSocketAddress addr = new InetSocketAddress(host, port);
    // 生成一个socketchannel
    schannel = SocketChannel.open(); // 连接到server
    schannel.connect(addr);
     
     
    } /**
     * 发送单个文件
     * 
     * @param fileType
     *            文件类型
     * @param file
     *            文件
     * @throws IOException
     */
    public void upload(int fileType, File file) throws IOException {
     
    Basic b=new Basic(file.getName(),file.length());
    raf = new RandomAccessFile(file, "r");
    fchannel = raf.getChannel(); ByteBuffer buffer1 = ByteBuffer.wrap(b.getbytes());
    MappedByteBuffer buffer2 = fchannel.map(FileChannel.MapMode.READ_ONLY, 0, fchannel.size());
      while (buffer1.hasRemaining()) {
     
        schannel.write(buffer1);
      }
     
      while (buffer2.hasRemaining()) {
        schannel.write(buffer2);
      }
     
      raf.close();
      fchannel.close();

       
    } /**
     * 
     * @param type
     *            文件类型
     * @param filePath
     *            文件路径,单个文件或文件夹路径
     * @throws IOException
     */
    public void upload(int type, String filePath) throws IOException {
    File file = new File(filePath);
    if (!file.exists()) {
    logger.error(file.getName() + " file not found!");
    return;
    }
    if (file.isFile()) {
    upload(type, file);
    }
    if (file.isDirectory()) {
    File[] files = file.listFiles();
    if (files != null && files.length > 0) {
    for (int i = 0; i < files.length; i++) {
    upload(type, files[i]);
    }
    }
    }
    } /**
     * 发送消息头
     * 
     * @param header
     * @throws IOException
     */
    public void send(MsgHeader header) throws IOException {

    } /**
     * 发送文件
     * 
     * @since
     * @param channel
     * @throws IOException
     */
    public void send(FileChannel channel) throws IOException {

    } /**
     * 关闭连接
     * @throws IOException 
     * 
     * @since
     */
    public void close() throws IOException {
     

    schannel.close();
    } public static void main(String args[]) throws IOException {
     
    Client client = new Client("localhost", 8848);
    client.upload(1, "c:/xcgdr4.txt");
     client.upload(0, "c:/3.txt");
       // client.upload(1, "c:/xcgdr4.txt");
     
     
     
    client.close();
      }
    }
    package x.t;import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.ObjectStreamException;
    import java.io.Serializable;public class Basic implements Serializable
    {  private static final long serialVersionUID = 34152235053678515L;
     
    String Filename;
    long filesize; public Basic()
    {

    }
    public Basic(String Filename,long filesize)
    {
    this.Filename=Filename;
    this.filesize=filesize; 
    }
      private void writeObject(java.io.ObjectOutputStream out) throws IOException {   
        // System.out.println("writeObject invoked1");   
         out.defaultWriteObject();
      
    }   
      
    private void readObject(java.io.ObjectInputStream in) throws IOException,   
            ClassNotFoundException {   
        System.out.println("readObject invoked2"); 
        in.defaultReadObject();
            
    }   
      
    private Object writeReplace() throws ObjectStreamException {   
        // System.out.println("writeReplace invoked3");   
        return this;   
    }   
      
    private Object readResolve() throws ObjectStreamException {   
        System.out.println("readResolve invoked4");   
        return this;   
    }   
      
    public byte[] getbytes() throws IOException  {   
    ByteArrayOutputStream baos = new ByteArrayOutputStream( );   
    ObjectOutputStream dos = new ObjectOutputStream(baos);   
    dos.writeObject( this);
     
     

        return baos.toByteArray();   
    }   

    public static Basic load( byte b[]) throws IOException, ClassNotFoundException  {   
     
    ByteArrayInputStream baos = new ByteArrayInputStream(b);   
    ObjectInputStream oos = new ObjectInputStream(baos);   
    Basic bs=(Basic) oos.readObject();
        
        return bs  ; 
    }   
     
    public void display()
    {
    System.out.println(Filename + filesize);
    }

    }
      class SerializableTest 
    {
    public static void main(String args[]) throws IOException, ClassNotFoundException
    {
    Basic u=new Basic("哈哈",12 );
     byte b1[]=u.getbytes( );
     Basic u2=new Basic("1哈哈",112 );
     byte b2[]= u2.getbytes( );
     byte b3[]=new byte[b2.length+2];
     for(int i=0;i<b2.length;i++)
     {
     b3[i]=b2[i];
     }
     b3[b2.length]=-123;
     b3[b2.length+1]=-13;
     Basic u1=new Basic();
    u1=(Basic)u1.load(b1);
    u1.display();

      u2=new Basic();
    u2=(Basic)u2.load(b3);
    u2.display();

    System.out.println(new String(b3));

    }
    }
     
      

  2.   


    package x.t;import java.io.File;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    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;
    import java.util.Set;public class Server implements Runnable
    {
    public int port; public Selector selector; public ServerSocketChannel sschannel = null; public Server(int port) throws IOException
    {
    this.port = port;
    // 打开服务器套接字通道
    sschannel = ServerSocketChannel.open();
    // 此通道将被置于非阻塞模式
    sschannel.configureBlocking(false);
    // 打开一个选择器
    selector = Selector.open();
    // 将 ServerSocket 绑定到特定地址(IP 地址和端口号)。
    sschannel.socket().bind(new InetSocketAddress(port));
    // 设置侦听端所选的异步信号OP_ACCEPT
    sschannel.register(selector, SelectionKey.OP_ACCEPT);
    } public void run()
    {
    try
    {
    System.out.println("Server started ...");
    System.out.println("Server listening on port: " + port);
    while (true)
    {
    // System.out.println("dfdf");
    // 察看是否有新的请求包括连接请求和现有连接的请求数据。
    int num = selector.select(); // 如果没有新的请求,将继续循环等待。
    if (num == 0)
    {
    continue;
    }
    // 获得被发现请求的关键字并一个一个的处理它们。
    Set keys = selector.selectedKeys(); Iterator it = keys.iterator();
    // System.out.println(keys.size()+"大小");
    while (it.hasNext())
    {
    System.out.println(keys.size()+"大小");
    SelectionKey key = (SelectionKey) it.next(); if (key.isAcceptable())
    {// 侦听端信号触发
    ServerSocketChannel server = (ServerSocketChannel) key
    .channel();
    // 接受一个新的连接
    SocketChannel sc = server.accept();
    // 设置为非阻塞
    sc.configureBlocking(false); // 设置该socket的异步信号OP_READ:当socket可读时,
    sc.register(selector, SelectionKey.OP_READ);
    }
    if (key.isReadable())
    {// 某socket可读信号 // 读取接收到的数据
    SocketChannel sc = (SocketChannel) key.channel(); ByteBuffer br = ByteBuffer.allocate(17479);
    int temp = 0;
    String path = "d:\\a\\";
    if ((temp = sc.read(br)) > 0)
    {
    System.out.println(temp + "temp");
    Basic b = Basic.load(br.array()); // File f=new File(path+b.Filename);
    // f.createNewFile();
    b.display();
    ByteBuffer brs = ByteBuffer .allocate((int) b.filesize  );
    int s = 0;
    int sum = 0;
    while ((s = sc.read(brs)) >= 0)
    {
    sum += s;
    System.out.println(s + "===" + sum + " ------------------------" + brs.array().length + "  " + (int) b.filesize + " " + b.getbytes().length + "  ");
    if (sum == b.filesize)
    break;
    }  sc.close();
    }
     
      
    }
     
    // 删除已处理完的key
      it.remove();
     
    //...处理SelectionKey...
    } //删去关键字,因为你已经处理过它们了。
    keys.clear();
    }
    } catch (Exception e)
    { } }}
      

  3.   

    一般的client不太适合用nio 用传统的bio足已....毕竟一般的client不会同时连接多个server...通常是1个所以维持一个线程很
      

  4.   

    ...结上面的..正常
    而server端也只在大量连接时才会显现效果比如 10000个client连接到一个server时...并且要注意对于常连接不太适合用nio还有像传输大数据报的也不太适合(当然这个只是个人感觉)。比较适合的是,大量client连接并频繁发送中小形报文的情况。。