Java Socket小案例(3)上传图片

来源:互联网 发布:有什么英语翻译软件 编辑:程序博客网 时间:2024/06/05 09:23

需求:客户端从本地读取图片,上传到服务器,服务器收到图片保存在本地,并向客户端反馈信息

分析

服务器:
源:网络输入流
目的:网络输出流、图片文件
操作的是图片,所以用字节流

//服务器public class PicUploadServer {    public static void main(String[] args) {        ServerSocket ss = null;        Socket s = null;        OutputStream fos = null;        try {            ss = new ServerSocket(6666);            s = ss.accept();            fos = new FileOutputStream("C:/Users/superman/Desktop/3.png");            InputStream in = s.getInputStream();            OutputStream out = s.getOutputStream();            byte[] buf = new byte[1024];            int len = -1;            while ((len = in.read(buf)) != -1) {                fos.write(buf, 0, len);                fos.flush();            }            out.write("上传成功".getBytes());        } catch (Exception e) {            e.printStackTrace();        } finally {            try {                fos.close();                s.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }}//客户端public class PicUploadClient {    public static void main(String[] args) {        Socket s = null;        InputStream fis = null;        try {            s = new Socket("127.0.0.1", 6666);            fis = new FileInputStream("C:/Users/superman/Desktop/1.png");            InputStream in = s.getInputStream();            OutputStream out = s.getOutputStream();            byte[] buf = new byte[1024];            int len = -1;            while ((len = fis.read(buf)) != -1) {                out.write(buf, 0, len);                // 易错点                out.flush();            }            // 易错点            s.shutdownOutput();            int i = in.read(buf);            System.out.println(new String(buf, 0, i));        } catch (Exception e) {            e.printStackTrace();        } finally {            try {                fis.close();                s.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }}