我有以下代碼。我似乎正在準確傳送內容。但是,圖像未被正確捕獲。我是Java新手。基本上,我是一名C,C++,Linux程序員。我想知道問題是逐行讀取緩衝區。我在這裏錯過了什麼嗎?通過JAVA中的TCP Socket在網絡上傳輸圖像無效?
這裏是socket服務器代碼 -
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
你爲什麼使用'PrintStream'?只需從InputStream中讀取並將其寫入OutputStream即可,而不會使用BR.readline,這裏是二進制數據,而不是純文本。您可能還想看一下[The try-with-resources Statement](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html),並確保您正確處理了您的資源 – MadProgrammer
「稍微」複雜[示例](http://stackoverflow.com/questions/26495165/i-get-only-one-image-while-transferring-in-a-loop-over-a-socket-in- java/26498434#26498434),但演示了通過套接字進行文件傳輸的基本原理。 – MadProgrammer