网络编程(客户端,服务端文件上传下载)
服务端
- 可以接收多个客户端请求
- 使用多线程实现
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(8888);
while (true){
new Thread(new Runnable() {
@Override
public void run() {
try{
Socket socket = serverSocket.accept();
BufferedInputStream bufferedInputStream = new BufferedInputStream(socket.getInputStream());
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("/Users/mima000000/Desktop/"+System.currentTimeMillis()+".jpeg"));
int len;
byte[] bytes = new byte[1024*8];
while ((len=bufferedInputStream.read(bytes))!=-1){
bufferedOutputStream.write(bytes,0,len);
}
System.out.println("文件上传成功");
OutputStream outputStream = socket.getOutputStream();
outputStream.write("上传成功".getBytes());
outputStream.close();
bufferedOutputStream.close();
socket.close();
}catch (Exception e){
System.out.println(e);
}
}
}).start();
}
}
}
客户端
import java.io.*;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8888);
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("/Users/mima000000/Desktop/1.jpeg"));
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(socket.getOutputStream());
int len;
byte[] temp = new byte[1024];
while ((len=bufferedInputStream.read(temp))!=-1){
bufferedOutputStream.write(temp,0,len);
}
socket.shutdownOutput(); // 表示通知服务端,写出完毕结束。
System.out.println("fild upload successful");
InputStream inputStream = socket.getInputStream();
byte[] arr = new byte[20];
inputStream.read(arr);
System.out.println(new String(arr));
inputStream.close();
bufferedInputStream.close();
socket.close();
}
}
我对任何唾手而得,快速,出自本能,即兴,含混的事物没有信心。我相信缓慢,平和,细水长流的力量,踏实,冷静。我不相信缺乏自律精神和不自我建设,不努力,可以得到个人或集体的解放。