当前位置:编程学习 > JAVA >>

一个socket传输文件的问题

程序是想实现模拟100个用户下载服务器端的一个文件,并计算每个线程下载所用时间,但以下这个程序只创建了100个线程,却没有计算出所用时间?希望各位大神能帮忙看看,小弟是新手!!!代码如下
服务器端:
package multithread.file;
import java.io.*;
import java.net.*;
import java.util.concurrent.*;

public class MultiThreadDLServer {

/**
 * @param args
 */

public static void main(String[] args) {
// TODO Auto-generated method stub
boolean flag=true;
try{
ExecutorService pool=Executors.newFixedThreadPool(100);
ServerSocket server=new ServerSocket(12345);
System.out.println("开始监听");
File fi=new File("D:\\MyWeb.aps");
         System.out.println("文件长度:" + (int) fi.length());
while(flag){
Socket socket=server.accept();//接受客户端连接
pool.execute(new Handler(socket));

}
//关闭
server.close();
pool.shutdown();
}catch(IOException e){
e.printStackTrace();
}

}

package multithread.file;

import java.net.Socket;
import java.io.*;

public class Handler implements Runnable {

private Socket socket=null;
//private String filePath = "D:\\MyWeb.aps";

Handler(Socket socket){
this.socket=socket;
}

@Override
public void run() {
// TODO Auto-generated method stub
        try{
         DataInputStream dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
            dis.readByte();

         DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream("D:\\MyWeb.aps")));
            DataOutputStream ps = new DataOutputStream(socket.getOutputStream());
            
            int bufferSize = 8192;
            byte[] buf = new byte[bufferSize];
            
            
            while (true) {        //(read=fis.read(buf))!=-1
            
             int read = 0;
              if (fis != null) {
                    read = fis.read(buf);
                }

                if (read == -1) {
                    break;
                }
                
               // if((read=fis.read(buf))!=-1){
                 ps.write(buf, 0, read);
                 ps.flush();
                
                
            }
            
            // 注意关闭socket链接哦,不然客户端会等待server的数据过来,
            // 直到socket超时,导致数据不完整。
            dis.close();
            fis.close();
            ps.close();
            socket.close();                
            System.out.println("文件传输完成");

        }catch (Exception e) {
            e.printStackTrace();
        }
        
}

}
package multithread.file;

import java.net.Socket;
import java.io.*;

public class Handler implements Runnable {

private Socket socket=null;
//private String filePath = "D:\\MyWeb.aps";

Handler(Socket socket){
this.socket=socket;
}

@Override
public void run() {
// TODO Auto-generated method stub
        try{
         DataInputStream dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
            dis.readByte();

         DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream("D:\\MyWeb.aps")));
            DataOutputStream ps = new DataOutputStream(socket.getOutputStream());
            
            int bufferSize = 8192;
            byte[] buf = new byte[bufferSize];
            
            
            while (true) {        //(read=fis.read(buf))!=-1
            
             int read = 0;
              if (fis != null) {
                    read = fis.read(buf);
                }

                if (read == -1) {
                    break;
                }
                
               // if((read=fis.read(buf))!=-1){
                 ps.write(buf, 0, read);
                 ps.flush();
                
                
            }
            
            // 注意关闭socket链接哦,不然客户端会等待server的数据过来,
            // 直到socket超时,导致数据不完整。
            dis.close();
            fis.close();
            ps.close();
            socket.close();                
            System.out.println("文件传输完成");

        }catch (Exception e) {
            e.printStackTrace();
        }
        
}

}
--------------------编程问答-------------------- 客户端:
package multithread.file;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MultiThreadDLClient {

/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
 int numTasks = 100;    
             
         ExecutorService exec = Executors.newCachedThreadPool();    
    
         for (int i = 0; i < numTasks; i++) {    
             exec.execute(createTask(i));    
        }    


}

private static Runnable createTask(final int taskID) {
// TODO Auto-generated method stub
return new Runnable(){
private Socket socket = null;    
    private int port=12345;
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("Task " + taskID + ":start");
try{
//System.out.print("hello");
long start = System.currentTimeMillis () ;

socket = new Socket("localhost", port); 
int bufferSize = 8192;
            byte[] buf = new byte[bufferSize];
                    int total=0;
                    DataInputStream inputStream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
                    
                    while (true) {
                        int read = 0;
                        /*if (inputStream != null) {
                            read = inputStream.read(buf);
                        }
                        total+=read;
                        if (read>0) 
                         total += read;*/
                       if((read=inputStream.read(buf))!=-1)
                        total+=read;
                        //if(read==-1)
                       else
                         break;
                        
                        double last = ( System.currentTimeMillis () - start ) * 1.0 / 1000 ; 
                        System.out.print( " downloaded " + total 
                             + "bytes in " + last + "s." );
                        socket.close();                
                        System.out.println("文件传输完成");
                   
}
}catch(IOException e){
e.printStackTrace();
//System.out.print("hello");
}

}
    
};

}

}
--------------------编程问答-------------------- 正好学到网络编程,拿去学一下,呵呵 --------------------编程问答-------------------- 稍微做了下修改你参考下吧

package com.zhangyz.www.socket;

import java.net.Socket;
import java.io.*;

public class Handler implements Runnable {

private Socket socket=null;

Handler(Socket socket){
this.socket=socket;
}

@Override
public void run() {
  try{

  DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream("e:\\temp\\equinox-SDK-3.8M6.zip")));
  DataOutputStream ps = new DataOutputStream(socket.getOutputStream());
   
  int bufferSize = 8192;
  byte[] buf = new byte[bufferSize];
   
   
  while (true) {
 
  int read = 0;
  if (fis != null) {
  read = fis.read(buf);
  }

  if (read == -1) {
  break;
  }
   
  ps.write(buf, 0, read);
  ps.flush();
   
   
  }

  fis.close();
  ps.close();
  socket.close();  
  System.out.println("文件传输完成");

  }catch (Exception e) {
  e.printStackTrace();
  }
   
}

}


package com.zhangyz.www.socket;

import java.io.*;
import java.net.*;
import java.util.concurrent.*;

public class MultiThreadDLServer {

/**
* @param args
*/

public static void main(String[] args) {
// TODO Auto-generated method stub
boolean flag=true;
try{
ExecutorService pool=Executors.newFixedThreadPool(2);
ServerSocket server=new ServerSocket(12345);
System.out.println("开始监听");
File fi=new File("e:\\temp\\equinox-SDK-3.8M6.zip");
  System.out.println("文件长度:" + (int) fi.length());
while(flag){
Socket socket=server.accept();//接受客户端连接
pool.execute(new Handler(socket));

}
//关闭
server.close();
pool.shutdown();
}catch(IOException e){
e.printStackTrace();
}

}
}



package com.zhangyz.www.socket;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MultiThreadDLClient {

/**
 * @param args
 */
public static void main(String[] args) {

int numTasks = 1;

ExecutorService exec = Executors.newCachedThreadPool();
for (int i = 0; i < numTasks; i++) {
exec.execute(createTask(i));
}
exec.shutdown();
}

private static Runnable createTask(final int taskID) {

return new Runnable() {
private Socket socket = null;
private int port = 12345;

@Override
public void run() {

System.out.println("Task " + taskID + ":start");
OutputStream out=null;
try {
out=new FileOutputStream("e:\\temp\\equinox-SDK-3.8M6.bak.zip");
long start = System.currentTimeMillis();

socket = new Socket("localhost", port);
int bufferSize = 8192;
byte[] buf = new byte[bufferSize];
int total = 0;
DataInputStream inputStream = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));

while (true) {
int read = 0;
if ((read = inputStream.read(buf)) != -1){
total += read;
out.write(buf, 0, read);
out.flush();
}
else
break;

double last = (System.currentTimeMillis() - start) * 1.0 / 1000;
System.out.println(" downloaded " + total + "bytes in "
+ last + "s.");
}
socket.close();
System.out.println("文件传输完成");
} catch (IOException e) {
e.printStackTrace();
}
finally{
if(out!=null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

}

};

}

}

--------------------编程问答-------------------- 我运行了你这个程序,但是还是算不出每个线程的所用时间? --------------------编程问答--------------------
引用 4 楼  的回复:
我运行了你这个程序,但是还是算不出每个线程的所用时间?


你直接在run()函数里面自己记录时间不就行了。

long timer = System.currentTimeMillis();
.....
timer = System.currentTimeMillis() - timer;
System.out.println("Spend: " + timer + "ms"); --------------------编程问答-------------------- 我在写一个模仿QQ。但是聊天代码不知道怎么写 --------------------编程问答-------------------- 马克一计,最近在搞网络编程 --------------------编程问答--------------------
引用 3 楼 zyz1985 的回复:
稍微做了下修改你参考下吧
Java code?1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253package com.zhangyz.www.socket; import java.net.Socket;import java……

你好,怎么样在不关闭socket连接的情况下,将所有的数据发送到客户端。下面是文章中的代码:

// 注意关闭socket链接哦,不然客户端会等待server的数据过来,  
// 直到socket超时,导致数据不完整。                  
fis.close();  
s.close();                  
System.out.println("文件传输完成");  
补充:Java ,  Java SE
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,