我有一個python服務器,我的java客戶端將連接到並連接後,python服務器將發送圖像到Java客戶端。我正在Java端獲得一個文件,但圖像已損壞,無法打開。它與原始圖像大小相同,但已損壞。如果有人能指出我做錯了什麼,那將會非常有幫助。謝謝你提前。python服務器和java客戶端:從python服務器發送到java客戶端時圖像已損壞
編輯:python服務器與python客戶端一起工作,所以我認爲它與Java代碼的問題。鏈接到Python客戶端和服務器:http://www.bogotobogo.com/python/python_network_programming_server_client_file_transfer.php
以下是我的代碼:
Python的服務器:
import socket # Import socket module
port = 2200 # Reserve a port for your service.
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
print 'Server listening....'
while True:
conn, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
data = conn.recv(1024)
print('Server received', repr(data))
filename='imagefile.jpg'
f = open(filename,'rb')
l = f.read(1024)
while (l):
conn.send(l)
print('Sent ',repr(l))
l = f.read(1024)
f.close()
print('Done sending')
conn.send('Thank you for connecting')
conn.close()
Java客戶端:
String usr2ConnectDefault = "127.0.0.1";
InetAddress ip = InetAddress.getLocalHost();
int port2ConnectDefault = 2200;
Socket socket;
BufferedReader in;
PrintWriter out;
System.out.print(ip.getHostAddress());
socket = new Socket(ip.getHostAddress(), port2ConnectDefault);
System.out.println("Connected to server...sending echo string");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
out.println("Begin transfer:");
int sizeOfFile = 32336;
byte[] fileData = new byte[sizeOfFile];
for (int i = 0; i < sizeOfFile; i++)
{
byte bite = (byte) in.read();
fileData[i] = bite;
System.out.println(fileData[i]);
}
// save file to disk
System.out.println(fileData);
FileOutputStream fos = null;
fos = new FileOutputStream("fileImage.png");
fos.write(fileData);
fos.close();
out.close();
// verify if request is OK
String readString = in.readLine();
in.close();
socket.close();
在Python服務器上,'f.close()'調用應該在while(l)'循環之外。這是張貼在這裏的錯字還是代碼中的錯誤? – User
進行了更改。對不起,不正確的縮進。 – Student
在**服務器上**不讀只讀'1024'讀取'os.path.getsize(filename)'然後在**客戶端上接收相同的大小** –