用 ServerSocket 写一个 接收图片A 并返回图片B的代码
时间: 2024-05-02 22:16:09 浏览: 60
以下是使用 ServerSocket 接收图片A 并返回图片B 的 Java 代码:
```java
import java.io.*;
import java.net.*;
public class ImageServer {
private static final int PORT = 8888; // 服务端口号
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Image server started on port " + PORT);
while (true) {
Socket socket = serverSocket.accept();
System.out.println("Client connected: " + socket.getInetAddress().toString());
// 读取客户端发送的图片A
InputStream inputStream = socket.getInputStream();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, len);
}
byte[] imageA = byteArrayOutputStream.toByteArray();
// 处理图片A并生成图片B
byte[] imageB = processImage(imageA);
// 返回图片B给客户端
OutputStream outputStream = socket.getOutputStream();
outputStream.write(imageB);
// 关闭连接
socket.close();
}
}
private static byte[] processImage(byte[] imageA) {
// TODO: 处理图片A并生成图片B
return imageA;
}
}
```
客户端发送图片A的代码可以参考以下示例:
```java
import java.io.*;
import java.net.*;
public class ImageClient {
private static final String SERVER_ADDRESS = "localhost"; // 服务端地址
private static final int SERVER_PORT = 8888; // 服务端口号
public static void main(String[] args) throws IOException {
Socket socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
System.out.println("Connected to server: " + socket.getInetAddress().toString());
// 发送图片A到服务端
OutputStream outputStream = socket.getOutputStream();
FileInputStream fileInputStream = new FileInputStream(new File("path/to/imageA.jpg"));
byte[] buffer = new byte[1024];
int len;
while ((len = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
fileInputStream.close();
// 接收服务端返回的图片B
InputStream inputStream = socket.getInputStream();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
buffer = new byte[1024];
while ((len = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, len);
}
byte[] imageB = byteArrayOutputStream.toByteArray();
// 保存图片B到本地
FileOutputStream fileOutputStream = new FileOutputStream(new File("path/to/imageB.jpg"));
fileOutputStream.write(imageB);
fileOutputStream.close();
// 关闭连接
socket.close();
}
}
```
注意,以上代码仅供参考,实际应用时需要根据具体需求进行修改。例如,图片处理部分需要根据实际情况进行实现。
阅读全文