/**
客户端,本来图片为 120KB,上传后变成122KB,求解呀!
*/
public class UploadFileClient {
public static void main(String[] args) throws IOException {
//1.创建Socket客户端服务对象
Socket s = new Socket("127.0.0.1",10051);
System.out.println("客户端启动!");
//System.out.println(InetAddress.getLocalHost());
//2.创建源,硬盘上的文件
BufferedInputStream bufr = new BufferedInputStream(new FileInputStream("D:\\a.jpg"));
//3.获取Socket输出流
BufferedOutputStream bufout = new BufferedOutputStream(s.getOutputStream());
OutputStream out = s.getOutputStream();
//4.定义缓冲区
int len = 0;
//5.将文件写入进Socket流中
while((len = bufr.read())!=-1)
{
bufout.write(len);
}
//告诉服务端数据写完了
s.shutdownOutput();
//6.获取服务端的反馈信息
BufferedReader bufin = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line = bufin.readLine();
System.out.println(line);
//7.关闭流
bufr.close();
bufout.close();
}
}
/**
服务端
*/
public class UploadFileServer {
public static void main(String[] args) throws IOException {
// 1.创建服务端对象
ServerSocket ss = new ServerSocket(10051);
System.out.println("服务端启动!");
// 2.监听客户端
Socket s = ss.accept();
System.out.println(s.getLocalAddress());
System.out.println(s.getInetAddress());
// 3.获取客户端中读取流
BufferedInputStream bufin = new BufferedInputStream(s.getInputStream());
// 4.创建目的地的,输入流
BufferedOutputStream bufw = new BufferedOutputStream(
new FileOutputStream("E:\\aa.jpg"));
// 5.读取Socket流中数据,将数据写到目的地中
int len = 0;
while ((len = bufin.read()) != -1) {
bufw.write(len);
}
// 6.将上传的结果反馈给客户端
PrintWriter pwout = new PrintWriter(s.getOutputStream(), true);
pwout.println("上传成功!");
// 7.关闭资源
bufw.close();
s.close();
}
}
|