美文网首页
2021-09-28 网络编程(TCP-上传图片)

2021-09-28 网络编程(TCP-上传图片)

作者: Denholm | 来源:发表于2021-10-08 20:53 被阅读0次

1.服务端读取客户端已有的图片数据
2.通过Socket输出流将数据发给服务端
3.读取服务端反馈信息
4.关闭资源

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class PicServer {

    public static void main(String[] args) throws Exception {
        ServerSocket server = new ServerSocket(10007);
        Socket accept = server.accept();
        InputStream is = accept.getInputStream();
        FileOutputStream fos = new FileOutputStream("E:\\server.png");
        int len;
        byte[] buf = new byte[1024];
        while ((len = is.read(buf)) != -1) {
            fos.write(buf, 0, len);
        }

        OutputStream out = accept.getOutputStream();
        out.write("上传成功".getBytes());

        fos.close();
        server.close();
        accept.close();
    }

}
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class PicClient {

    public static void main(String[] args) throws Exception {
        Socket socket = new Socket("192.168.1.6", 10007);
        FileInputStream fis = new FileInputStream("E:\\test.jpg");
        OutputStream os = socket.getOutputStream();
        byte[] buf = new byte[1024];
        int len;
        while ((len = fis.read(buf)) != -1) {
            os.write(buf, 0, len);
        }

        InputStream is = socket.getInputStream();
        socket.shutdownOutput(); // 告诉服务器数据已写完
        byte[] bufIn = new byte[1024];
        int num = is.read(bufIn);
        System.out.println(new String(bufIn, 0, num));

        socket.close();
        fis.close();
    }

}

相关文章

网友评论

      本文标题:2021-09-28 网络编程(TCP-上传图片)

      本文链接:https://www.haomeiwen.com/subject/lparnltx.html