【发布时间】:2012-02-06 07:51:51
【问题描述】:
我正在尝试一次将二进制文件从服务器传输到客户端一个字节块。但是,我遇到了传输 8kb 时卡住的问题。该文件通常大于 1mb,字节数组的大小为 1024。我相信它与我的 while 循环有关,因为它不会关闭我的连接。有什么帮助吗?谢谢
客户
import java.io.*;
import java.net.Socket;
public class FileClient {
public static void main(String[] argv) throws IOException {
Socket sock = new Socket("localhost", 4444);
InputStream is = null;
FileOutputStream fos = null;
byte[] mybytearray = new byte[1024];
try {
is = sock.getInputStream();
fos = new FileOutputStream("myfile.pdf");
int count;
while ((count = is.read(mybytearray)) >= 0) {
fos.write(mybytearray, 0, count);
}
} finally {
fos.close();
is.close();
sock.close();
}
}
}
服务器
import java.net.*;
import java.io.*;
public class FileServer {
public static void main(String[] args) throws IOException {
ServerSocket servsock = new ServerSocket(4444);
File myFile = new File("myfile.pdf");
FileInputStream fis = null;
OutputStream os = null;
while (true) {
Socket sock = servsock.accept();
try {
byte[] mybytearray = new byte[1024];
fis = new FileInputStream(myFile);
os = sock.getOutputStream();
int count;
while ((count = fis.read(mybytearray)) >= 0) {
os.write(mybytearray, 0, count);
}
os.flush();
} finally {
fis.close();
os.close();
sock.close();
System.out.println("Socket closed");
}
}
}
}
【问题讨论】:
标签: java sockets tcp filestream