本周论坛作业题那个上传图片文件那题,最后一步Server端给出反馈信息老是为null,也不知道哪里不对,只能求教大神了
Server端:
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.net.ServerSocket;
- import java.net.Socket;
- public class UploadServerDemo {
- public static void main(String[] args) throws IOException {
- ServerSocket ss = new ServerSocket(10086);
- // 监听客户端对象
- Socket s = ss.accept();
- // 获取输入流
- BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
- BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("上传图片.jpg"));
- byte[] bys = new byte[2048];
- int len = 0;
- while ((len = bis.read(bys)) != -1) {
- bos.write(bys,0,len);
- bos.flush();
- }
- // 给出反馈,获取输出流
- PrintWriter out = new PrintWriter(s.getOutputStream());
- out.println("文件上传成功");
- // 释放资源
- bos.close();
- s.close();
- ss.close();
- }
- }
复制代码
Client端:
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.BufferedReader;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.net.Socket;
- import java.util.Scanner;
- public class UploadClientDemo {
- public static void main(String[] args) throws IOException {
- //设置Socket
- Socket s = new Socket("192.168.16.100",10086);
-
- System.out.println("请输入上传图片地址:");
- Scanner sc = new Scanner(System.in);
- String path = sc.nextLine();
- sc.close();
-
- //封装输入输出流
- BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path));
- BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
-
- //传递数据
- byte[] bys = new byte[2048];
- int len = 0;
- while ((len = bis.read(bys))!= -1) {
- bos.write(bys, 0, len);
- bos.flush();
- }
- s.shutdownOutput();
-
- BufferedReader brServer = new BufferedReader(new InputStreamReader(
- s.getInputStream()));
- String server = brServer.readLine();
- System.out.println("server反馈信息是:" + server);
- // 释放资源
- bis.close();
- s.close();
- }
- }
复制代码 |