使用Java在套接字上发送文件

时间:2012-02-28 03:50:18

标签: java file sockets networking

我在尝试通过套接字将文件从服务器程序发送到客户端程序时遇到问题。所以我公平地尝试将其分成字节,但到目前为止我还没有取得任何成功。服务器也必须是并发的,所以我不确定在哪里放置代码来发送文件。

由于

编辑:

这是我到目前为止尝试过的代码,目前它将文件的副本传输到其意图,但文件大小为零字节:(

在Protocol类中:

try {
    File program = new File("./src/V2AssignmentCS/myProgram.jar");

byte[] mybytearray = new byte[4096];

FileInputStream fis = new FileInputStream(program);

BufferedInputStream bis = new BufferedInputStream(fis);

bis.read(mybytearray, 0, mybytearray.length);

OutputStream os = sock.getOutputStream();

System.out.println("Sending...");

os.write(mybytearray, 0, mybytearray.length);

os.flush();

} catch (IOException e) {

        System.err.println("Input Output Error: " + e);

    }

在客户端:

long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
// localhost for testing

// receive file
byte [] mybytearray  = new byte [ServerResponse.programSize()];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("./src/V2AssignmentCS/newProgram.jar");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;

// thanks to A. Cádiz for the bug fix
do {
   bytesRead =
      is.read(mybytearray, current, (mybytearray.length-current));
   if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);

bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end-start);
bos.close();
sock.close();

1 个答案:

答案 0 :(得分:3)

bis.read(mybytearray, 0, mybytearray.length);

您忽略此方法返回的结果代码。检查Javadoc。这不是你所期望的那样。

os.write(mybytearray, 0, mybytearray.length);

这里你正在编写4096个字节。那是你的意图吗?

bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
// thanks to A. Cádiz for the bug fix
do {
   bytesRead =
      is.read(mybytearray, current, (mybytearray.length-current));
   if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);

在Java中复制流的规范方法,你应该在两端使用如下:

int count;
byte[] buffer = new byte[8192]; // or whatever you like
while ((count = in.read(buffer)) > 0)
{
  out.write(buffer, 0, count);
}
out.close();
in.close();