[JAVA]Socket 图片流的传输

import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) {
        System.out.println("--->server");
        try {
            ServerSocket server = new ServerSocket(4700);
            Socket socket = server.accept();
            DataInputStream dis = new DataInputStream(socket.getInputStream());
            String type = dis.readUTF();
            System.out.println("type: " + type);

            // long len = dis.readLong();
            // System.out.println("len: " + len);

            byte[] buff = new byte[1024];
            OutputStream os = new FileOutputStream("C:/Users/Administrator/Desktop/dts.jpg");
            int len = -1;
            while ((len = dis.read(buff)) != -1) {
                os.write(buff, 0, len);
            }
            os.flush();
            os.close();
            dis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("server--->");
    }
}
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.Socket;

public class Client {
    public static void main(String args[]) {
        try {
            Socket socket = new Socket("127.0.0.1", 4700);
            if (socket.isConnected()) {
                System.out.println("isConnected");
                DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
                dos.writeUTF("STREAM");
                File file = new File("C:/Users/Administrator/Desktop/src.jpg");
                // dos.writeLong(file.length());
                byte[] buff = new byte[1024];
                InputStream inputStream = new FileInputStream(file);
                int len = -1;
                while ((len = inputStream.read(buff)) != -1) {
                    dos.write(buff, 0, len);
                }
                inputStream.close();
                dos.flush();
                dos.close();
            }
            // socket.close(); // 关闭Socket
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

[JAVA]Socket 图片流的传输,布布扣,bubuko.com

[JAVA]Socket 图片流的传输

上一篇:java 反射机制


下一篇:Operation System - Peterson's Solution算法 解决多线程冲突