客户端
package cn.dali4.code03ex;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
/*文件上传案例:读取本地文件,上传至服务器,读取服务器回写数据。
*
* 数据源:C:\Users\Administrator\Desktop\sxmy.jpg
* 目的地:服务器
*
* 实现步骤:
* 1.创建本地文件字节输入流读取文件
* 2.创建一个客户端Socket,绑定服务器IP机器port
* 3.使用socket对象方法获取字节输出流
* 4.使用字节输出流把读取的数据写入
* 5.使用获取字节输入流
* 6.使用网络字节输入流read方法读取服务器回写数据
* 7.释放资源*/
public class Client {
public static void main(String[] args) throws IOException {
Socket sc = new Socket("127.0.0.1",6666);//2
OutputStream os = sc.getOutputStream();//3
byte[] byte01 = new byte[1024];
try (FileInputStream fis = new FileInputStream("C:\\Users\\Administrator\\Desktop\\sxmy.jpg")) {//1
int len = 0;
while ((len = fis.read(byte01)) != -1) {
os.write(byte01);
}//4
} catch (IOException e) {
e.printStackTrace();
}
sc.shutdownOutput();
InputStream is = sc.getInputStream();//5
int len = 0;
while ((len = is.read(byte01)) != -1) {
System.out.println(new String(byte01, 0, len));
}//6
sc.close();//7
}
}
服务端
package cn.dali4.code03ex;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
/*实现步骤:
* 1.创建一个服务器socket对象,和系统要指定的端口
* 2.使用accept方法获取客户端的socket对象
* 3.获取网络字节输入流对象
* 4.判断存放的文件夹是否存在,不存在则创建
* 5.使用字节输入流对象的read方法读取数据
* 6.使用本地字节输出流写入到本地硬盘
* 7.使用网络字节输出流回写数据
* 8.释放资源*/
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(6666);
Socket sc = ss.accept();
File file = new File("C:\\Users\\Administrator\\Desktop\\山下美月");
if(!file.exists()){
file.mkdirs();
}
InputStream is = sc.getInputStream();
byte [] bytes = new byte[1024];
int len = 0;
FileOutputStream fos = new FileOutputStream(file+"\\sxmy.jpg");
while((len = is.read(bytes))!=-1){
fos.write(bytes);
}
sc.getOutputStream().write("收到".getBytes());
fos.close();
sc.close();
ss.close();
}
}