用 ServerSocket 写一个 接收图片A ,保存为图片B,并拿到D盘图片C并返回给客户端,客户端接收之后保存为D盘图片D
时间: 2024-05-11 12:19:39 浏览: 6
以下是一个简单的 Java 代码实现:
服务器端:
```java
import java.io.*;
import java.net.*;
public class ImageServer {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务器已启动,等待客户端连接...");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("客户端已连接");
// 读取图片A
InputStream is = socket.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
byte[] bytes = new byte[1024];
int len = 0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((len = bis.read(bytes)) != -1) {
baos.write(bytes, 0, len);
}
byte[] imageBytes = baos.toByteArray();
// 保存图片B
FileOutputStream fos = new FileOutputStream("B.jpg");
fos.write(imageBytes);
fos.close();
// 发送图片C
FileInputStream fis = new FileInputStream("D:/C.jpg");
BufferedInputStream bis2 = new BufferedInputStream(fis);
OutputStream os = socket.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(os);
while ((len = bis2.read(bytes)) != -1) {
bos.write(bytes, 0, len);
}
bos.flush();
// 关闭连接
bos.close();
bis2.close();
fis.close();
baos.close();
bis.close();
is.close();
socket.close();
System.out.println("客户端已断开连接");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
客户端:
```java
import java.io.*;
import java.net.*;
public class ImageClient {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8888);
// 发送图片A
FileInputStream fis = new FileInputStream("D:/A.jpg");
BufferedInputStream bis = new BufferedInputStream(fis);
OutputStream os = socket.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(os);
byte[] bytes = new byte[1024];
int len = 0;
while ((len = bis.read(bytes)) != -1) {
bos.write(bytes, 0, len);
}
bos.flush();
// 接收图片C并保存为图片D
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("D.jpg");
BufferedOutputStream bos2 = new BufferedOutputStream(fos);
while ((len = is.read(bytes)) != -1) {
bos2.write(bytes, 0, len);
}
bos2.flush();
// 关闭连接
bos2.close();
fos.close();
is.close();
bos.close();
os.close();
bis.close();
fis.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```