private void receiveImage(Socket socket, String filename) throws IOException { InputStream is = socket.getInputStream(); FileOutputStream fos = new FileOutputStream(filename); byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { fos.write(buffer, 0, len); } System.out.println(filename + " received."); }帮我修改这段代码让sendImage方法能够发送图片消息 receiveImage方法能够接受图片并且将图片显示出来
时间: 2024-01-12 07:02:19 浏览: 66
下面是修改后的代码,其中sendImage方法和receiveImage方法都加了注释,方便您理解:
```java
// 发送图片消息
private void sendImage(Socket socket, String filename) throws IOException {
// 读取图片文件
FileInputStream fis = new FileInputStream(filename);
// 获取socket输出流
OutputStream os = socket.getOutputStream();
// 定义缓冲区
byte[] buffer = new byte[1024];
int len;
// 循环读取图片文件并写入socket输出流
while ((len = fis.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
// 关闭输入流和socket输出流
fis.close();
os.close();
System.out.println(filename + " sent.");
}
// 接受图片并显示
private void receiveImage(Socket socket, String filename) throws IOException {
// 获取socket输入流
InputStream is = socket.getInputStream();
// 创建输出流,用于将图片写入文件
FileOutputStream fos = new FileOutputStream(filename);
// 定义缓冲区
byte[] buffer = new byte[1024];
int len;
// 循环读取socket输入流并写入文件
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
// 关闭输入流和输出流
fos.close();
is.close();
// 显示图片
Image image = new Image(new FileInputStream(filename));
ImageView imageView = new ImageView(image);
Stage stage = new Stage();
stage.setScene(new Scene(new StackPane(imageView), image.getWidth(), image.getHeight()));
stage.show();
System.out.println(filename + " received and displayed.");
}
```
您可以将上述代码粘贴到您的项目中,然后在需要发送图片或者接收并显示图片的地方调用对应的方法即可。请注意,这段代码只能处理单张图片,如果需要处理多张图片,您需要自己实现相应的逻辑。
阅读全文