2014-12-02 126 views
25

我已經成功地將文件內容(圖像)複製到新文件。但是,當我通過TCP套接字嘗試相同的事情時,我正面臨着問題。服務器循環不退出。客戶端循環在到達EOF時退出,但服務器無法識別EOF。通過Python中的TCP套接字發送文件

下面的代碼:

服務器

import socket    # Import socket module 

s = socket.socket()   # Create a socket object 
host = socket.gethostname() # Get local machine name 
port = 12345     # Reserve a port for your service. 
s.bind((host, port))  # Bind to the port 
f = open('torecv.png','wb') 
s.listen(5)     # Now wait for client connection. 
while True: 
    c, addr = s.accept()  # Establish connection with client. 
    print 'Got connection from', addr 
    print "Receiving..." 
    l = c.recv(1024) 
    while (l): 
     print "Receiving..." 
     f.write(l) 
     l = c.recv(1024) 
    f.close() 
    print "Done Receiving" 
    c.send('Thank you for connecting') 
    c.close()    # Close the connection 

客戶

import socket    # Import socket module 

s = socket.socket()   # Create a socket object 
host = socket.gethostname() # Get local machine name 
port = 12345     # Reserve a port for your service. 

s.connect((host, port)) 
s.send("Hello server!") 
f = open('tosend.png','rb') 
print 'Sending...' 
l = f.read(1024) 
while (l): 
    print 'Sending...' 
    s.send(l) 
    l = f.read(1024) 
f.close() 
print "Done Sending" 
print s.recv(1024) 
s.close      # Close the socket when done 

以下是截圖:

服務器 Server

客戶 Client

編輯1:額外的數據複製。使文件「不完整」。 第一列顯示已收到的圖像。它似乎比發送的更大。因此,我無法打開圖像。這似乎是一個損壞的文件。

File sizes

編輯2:這是我如何做到這一點在控制檯中。這裏的文件大小是一樣的。 Python Console Same file sizes

回答

18

客戶需要通知其發送完,使用socket.shutdown(不socket.close其關閉兩個讀插座/寫作部分):

... 
print "Done Sending" 
s.shutdown(socket.SHUT_WR) 
print s.recv(1024) 
s.close() 

UPDATE

客戶端發送Hello server!給服務器;寫入服務器端的文件。

s.send("Hello server!") 

刪除上面的行以避免它。

+0

謝謝!我試過這個,但它仍然在循環中。我認爲問題在於客戶端發送永遠不會發送EOF,因爲一旦它到達EOF,它就會跳出循環,並且永遠不會發送給服務器。這是錯誤嗎? – 2014-12-02 04:37:18

+2

@SwaathiK,啊,客戶端正在等待數據,發送完成後。我更新了答案。請檢查一下。 – falsetru 2014-12-02 04:38:10

+0

非常感謝!它像一個魅力。但是我還有一個問題,爲什麼文件不能在服務器端進行重構?它複製一切,但文件不完整。我希望我有道理。 – 2014-12-02 04:49:24

0

問題是server.py在啓動時收到的額外13個字節。解決在while循環之前兩次寫入「l = c.recv(1024)」,如下所示。

print "Receiving..." 
l = c.recv(1024) #this receives 13 bytes which is corrupting the data 
l = c.recv(1024) # Now actual data starts receiving 
while (l): 

這樣可以解決問題,用不同的格式和文件大小嚐試。如果有人知道這個起始13字節是指什麼,請回復。

+1

我認爲「你好服務器!」是你正在尋找的13個字節。 – Alex 2015-06-30 09:45:14

6

刪除下面的代碼

s.send("Hello server!") 

,因爲您的發送s.send("Hello server!")到服務器,讓你的輸出文件是較爲大小。裏面while True

0

認沽文件一樣幫了我這麼

while True: 
    f = open('torecv.png','wb') 
    c, addr = s.accept()  # Establish connection with client. 
    print 'Got connection from', addr 
    print "Receiving..." 
    l = c.recv(1024) 
    while (l): 
     print "Receiving..." 
     f.write(l) 
     l = c.recv(1024) 
    f.close() 
    print "Done Receiving" 
    c.send('Thank you for connecting') 
    c.close()