Reputation: 1451
I am very new to Python and have a basic question, can a client side of a network socket connection make receive data? In my question, the client is the one who initiates the connection, which is probably obvious but I wanted to be clear. I ask because I have another server and client (both python) that allows the server to receive a file from the client. It works perfectly but I cannot get an example where the client receives a file. Python keeps telling me that the pipe has been broken and I suspect its because on the client side I use the line data = mysocket.recv(1024)
. My suspicion is that client doesn't see any data flowing and thus closes the connection to the server. The server sees it as a broken pipe. The server and client are below.
server:
#libraries to import
import socket
import os
import sys
import M2Crypto as m2c
#information about the server the size of the message being transferred
server_address = '10.1.1.2'
key_port = 8888
max_transfer_block = 1024
FILE = open("sPub.pem","r")
#socket for public key transfer
keysocket = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
keysocket.bind((server_address, key_port))
keysocket.listen(1)
while 1:
conn, client_addr = keysocket.accept()
print 'connected by', client_addr
#sends data to the client
data = FILE.read()
keysocket.sendall(data)
keysocket.close()
Client:
# the specified libraries
import socket
import M2Crypto as m2c
#file to be transferred
FILE = open("test.txt", "r")
#address of the server
server_addr = '10.1.1.2'
#port the server is listening on
dest_port = 8888
data = FILE.read()
#Creates a socket for the transfer
mysocket = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
mysocket.connect( (server_addr, dest_port) )
data = mysocket.recv(1024)
print data
#creates a new file to store the msg
name = "serverPubKey.pem"
#opens the new file and writes the msg to it
FILE = open (name, "w")
FILE.write(data)
#closes the socket.
mysocket.close()
I would appreciate any help on the matter. Thanks!
Upvotes: 2
Views: 6888
Reputation: 1080
Also, adding onto the previous comment, a good test sometimes is to repeat the receive a few times. The chance of the one pass catching the information the server sends is unlikely.
something like this
nreceive = True#nreceive = Not Received
ticks = 0
f = None
while nreceive and ticks < 101:#try to get the info 100 times or until it's received
ticks+=1
try:
f = mysocket.makefile('rb')
if not f == None:
nreceive = False
except:
pass
data = f.read(1024)
Upvotes: 0
Reputation: 226231
In applications like this, it is sometimes helpful to bypass the low level detail and use socket.makefile with its higher-level API instead.
In the client close, replace:
data = mysocket.recv(1024)
with:
f = mysocket.makefile('rb')
data = f.read(1024) # or any other file method call you need
The source code for ftplib shows how to do this in production code.
Upvotes: 1