📅  最后修改于: 2023-12-03 14:42:20.084000             🧑  作者: Mango
本文将介绍使用 Java 套接字通过网络发送图像的方法。在使用该方法前,需先了解 Java 网络编程基础知识及图像操作相关知识。
public class Server {
public static final int PORT = 8888;
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Server started.");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("Accept client: " + socket.getInetAddress());
DataInputStream dis = new DataInputStream(socket.getInputStream());
byte[] data = new byte[dis.available()];
dis.read(data);
// 保存文件
File file = new File("image.png");
FileOutputStream fos = new FileOutputStream(file);
fos.write(data);
fos.flush();
System.out.println("Save image done.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Client {
public static final String HOST = "localhost";
public static final int PORT = 8888;
public static void main(String[] args) {
try {
Socket socket = new Socket(HOST, PORT);
// 读取本地文件
File file = new File("image.png");
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[fis.available()];
fis.read(data);
fis.close();
// 发送图像数据
OutputStream os = socket.getOutputStream();
os.write(data);
os.flush();
System.out.println("Send image done.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意:本文未涉及图像的具体操作和展示,可根据需求进行相关操作。另外,在实际应用中,图像数据的传输需加密和压缩等处理,以保证数据安全和传输效率。