我有以下代码。我似乎准确地流式传输内容。但是,图像未正确捕获。我是Java新手。基本上,我是一名C,C ++,Linux程序员。我想知道问题是逐行读取缓冲区。我在这里错过了什么吗?
这是套接字服务器代码 -
import java.io.*;
import java.net.*;
public class ImageSocketServer {
public static void main(String args[]) throws IOException
{
ImageSocketServer imageServer = new ImageSocketServer();
imageServer.run();
}
private void run() throws IOException {
// TODO Auto-generated method stub
ServerSocket serverSock = new ServerSocket(1025);
Socket sock = serverSock.accept();
InputStream imagetoShare = new BufferedInputStream(new FileInputStream("/export/home/joshis1/Lizard.png"));
PrintStream imageSend = new PrintStream( sock.getOutputStream());
imageSend.print(imagetoShare);
}
}
这是套接字客户端代码 -
import java.io.*;
import java.net.*;
public class ImageSocketClient {
public static void main(String args[]) throws IOException
{
ImageSocketClient imageClient = new ImageSocketClient();
ImageSocketClient.run();
}
private static void run() throws UnknownHostException, IOException
{
// TODO Auto-generated method stub
BufferedWriter bufWriter = null;
bufWriter = new BufferedWriter(new FileWriter(
"/export/home/joshis1/file1.png"));
Socket sock = new Socket("localhost", 1025);
InputStreamReader IR = new InputStreamReader(sock.getInputStream());
BufferedReader BR = new BufferedReader(IR);
String data;
while ((data = BR.readLine()) != null)
{
System.out.println("Shreyas got the data");
bufWriter.write(data);
}
bufWriter.close();
}
}
我看到源图像的大小 -
$ ls -l Lizard.png
-rw-rw-r-- 1 joshis1 joshis1 19071522 May 29 15:46 Lizard.png
and the destination image is wrongly copied -
$ ls -l file1.png
-rw-rw-r-- 1 joshis1 joshis1 34 May 29 17:38 file1.png
答案 0 :(得分:4)
首先,您的imageSend.print(imagetoShare);
通过InputStream
的字符串表示发送,这解释了文件的小内容。你需要创建一个从imagetoShare
读取的循环(虽然你可能想要更好地命名,它不是图像,它是一个流)并将数据写入输出流(搜索典型的读取 - 写循环)。
其次,您使用的PrintStream
用于将字符数据写入OutputStream
。您想使用BufferedOutputStream
。
答案 1 :(得分:0)
由于错误使用各种java.io
类,代码中存在各种错误。
1。)您正在使用PrintStream
的{{1}}方法。这不是复制流的内容,而只是写一个对象的文本表示。
2.。)在您的客户端中,您使用的是print(Object o)
和Reader
个类。这些用于处理字符数据,而图像是原始二进制数据。考虑到编码,不可打印的字符等,你会遇到很多麻烦。
将其打包:使用普通Writer
和BufferedInputStream
来进行输入和输出。你必须在一些循环中将它全部包装起来,因为你一次只能读取一堆字节。