1,多线程接收文件
1,线程文件
public Socket socket;
public MyThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
String ThreadName = Thread.currentThread().getName();
System.out.println(ThreadName + "正在等待连接");
System.out.println(ThreadName + "连接成功,准备接受文件");
InputStream is = socket.getInputStream();
OutputStream os = new FileOutputStream((ThreadName + "/1.12.png"));
byte[] bytes = new byte[1024];
int len;
while ((len = is.read(bytes)) != -1) {
os.write(bytes, 0, len);
}
System.out.println("接受完毕,发送接受完毕给客户端");
OutputStream outputStream = socket.getOutputStream();
outputStream.write("发送完毕".getBytes(StandardCharsets.UTF_8));
is.close();
os.close();
} catch (IOException e) {
e.getStackTrace();
}
}
2,服务器端文件
public static void main(String[] args) throws IOException {
System.out.println("服务器端启动");
ServerSocket serverSocket = new ServerSocket(10000);
while (true) {
Socket socket = serverSocket.accept();
MyThread myThread = new MyThread(socket);
myThread.start();
}
}
3,客户端文件
public static void main(String[] args) throws IOException {
System.out.println("客户端正在启动");
Socket socket = new Socket("127.0.1.0", 10000);
System.out.println("连接成功,输入1传输文件");
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
if (num == 1) {
InputStream is = new FileInputStream("D:\\java\\text\\abc.png");
FileOutputStream os = (FileOutputStream) socket.getOutputStream();
byte[] bytes = new byte[1024];
int len;
while ((len = is.read(bytes)) != -1) {
os.write(bytes, 0, len);
}
socket.shutdownOutput();
BufferedReader bufferedReader=new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String line;
while ((line=bufferedReader.readLine())!=null){
System.out.println(line);
}
bufferedReader.close();
os.close();
is.close();
socket.close();
}
}
服务器端可以接收多个客户端传文件,并不是等待传送结束后再开启新的传送