import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;public class FileServer {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8888);
while (true) {
Socket socket = server.accept();
new Thread(() -> {
try {
FileOutputStream fos = new FileOutputStream("D:\\" + System.currentTimeMillis() + ".mp3");
BufferedOutputStream bos = new BufferedOutputStream(fos);
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
byte[] bytes = new byte[1024];
int len = 0;
while ((len = bis.read(bytes)) != -1) {
bos.write(bytes, 0, len);
bos.flush();
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}).start();
System.out.println("end");
}
}
}
/*
从Client中发送了一个mp3文件到Server端,Server端多线程的方式处理了发送请求,并存储在了硬盘中
上面的代码中bos.flush()已经执行完毕,线程结束,但是在Java运行结束之前文件一直处于0KB的状态,
手动结束JAVA运行之后才能看见实际的文件。必须在socket.close()前加上fos.close才能正常运行,
所以客户端运行结束之后文件数据已经存储在服务器端的缓冲流中,但并未被写出。求大神指导,为什么必须要
将流关闭之后一次性的看到数据被写入到硬盘中;
*/
import java.io.*;
import java.net.Socket;public class FileClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8888);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\f.mp3"));
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
byte[] bytes = new byte[1024];
int len = 0;
while ((len = bis.read(bytes)) != -1) {
bos.write(bytes, 0, len);
}
bos.flush();
socket.close();
}
}
import java.net.ServerSocket;
import java.net.Socket;public class FileServer {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8888);
while (true) {
Socket socket = server.accept();
new Thread(() -> {
try {
FileOutputStream fos = new FileOutputStream("D:\\" + System.currentTimeMillis() + ".mp3");
BufferedOutputStream bos = new BufferedOutputStream(fos);
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
byte[] bytes = new byte[1024];
int len = 0;
while ((len = bis.read(bytes)) != -1) {
bos.write(bytes, 0, len);
bos.flush();
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}).start();
System.out.println("end");
}
}
}
/*
从Client中发送了一个mp3文件到Server端,Server端多线程的方式处理了发送请求,并存储在了硬盘中
上面的代码中bos.flush()已经执行完毕,线程结束,但是在Java运行结束之前文件一直处于0KB的状态,
手动结束JAVA运行之后才能看见实际的文件。必须在socket.close()前加上fos.close才能正常运行,
所以客户端运行结束之后文件数据已经存储在服务器端的缓冲流中,但并未被写出。求大神指导,为什么必须要
将流关闭之后一次性的看到数据被写入到硬盘中;
*/
import java.io.*;
import java.net.Socket;public class FileClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8888);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\f.mp3"));
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
byte[] bytes = new byte[1024];
int len = 0;
while ((len = bis.read(bytes)) != -1) {
bos.write(bytes, 0, len);
}
bos.flush();
socket.close();
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货