Socket实现文件上传
文件上传的步骤:
服务器端步骤:
创建ServerSocket
调用accept获得客户端Socket
定义字节数组
创建文件输出流,获得客户端输入流
循环读取输入流的字节,写入到文件输出流
客户端步骤:
创建Socket
获得socket对象输出流
创建文件输入流
循环读取文件输入流字节,写入到输出流
代码实现:
服务器端:
public class FileServer {
public static final int PORT = 8888;
public static final String PATH = "D:\\upload\\";
public void start(){
System.out.println("start...");
try ( //创建服务器端对象
ServerSocket server = new ServerSocket(PORT);){
while (true){
Socket socket = server.accept();
try ( //创建文件输出流和网络输入流
DataInputStream in = new DataInputStream(socket.getInputStream());
//读取哭护短发来的文件名,创建文件输出流
FileOutputStream out = new FileOutputStream(PATH+in.readUTF())){
int len = 0;
byte[] buffer = new byte[1024];
while ((len = in.read(buffer)) != -1){
out.write(buffer,0,len);
}
System.out.println("服务器保存完毕!");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new FileServer().start();
}
}
客户端:
public class FileClient {
/**
* 发送文件
*/
public void sendFile(String ip,int port,String path){
File file = new File(path);
try (
//创建连接,创建文件输入流,网络输出流
Socket socket = new Socket(ip,port);
InputStream in = new FileInputStream(path);
DataOutputStream out = new DataOutputStream(socket.getOutputStream())){
//先发送文件给服务器
out.writeUTF(file.getName());
out.flush();
//读取本地文件,写入到网络输出流中
int len = 0;
byte[] buffer = new byte[1024];
while ((len = in.read(buffer)) != -1){
out.write(buffer,0,len);
}
System.out.println("客户端发送完毕!");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new FileClient().sendFile("192.168.31.226",8888,"C:\\Users\\admin\\Desktop\\C.txt");
}
}
实现效果: