sending file through socket in python 3 - python

In the code below I've tried to send an image using the python socket module in one machine to another machine. So I have 2 files: client.py and Server.py
as I figured it out the problem is when I read the image(as bytes) at the client machine and then the server tries to receive the file, at that moment when sending process is done before the receiving process then the error below occurs at line 13 of the client code:
BrokenPipeError: [Errno 32] Broken pipe
I want to find out what this error is and why does it occur in my code.
Server.py
import socket
host = '192.168.1.35'
port = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(1)
while True:
conn , addr = s.accept()
data = conn.recv(1024)
with open(r"C:\Users\master\Desktop\music.jpg",'wb') as f:
f.write(data)
# conn.send(b'done')
data = conn.recv(1024)
if not data:
break
conn.send(b'done')
conn.send(b'done')
conn.close()
s.close()
Client.py
import socket
def main():
HOST = '192.168.1.35'
PORT = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
f = open('/home/taha/Desktop/f.jpg','rb')
data = f.read()
s.sendfile(f)
if s.recv(1024) == b'done':
f.close()
s.close()
if __name__ == '__main__':
main()

You are closing the server connection before the client read the โ€œdoneโ€

Related

Sendign a file over TCP connection

Im trying to send a file over TCP connection and im spected to receive an accio command but, im having trobule doing that, im getting this error:PS C:\Users\mpgm1\PycharmProjects\pythonProject1> py client.py 131.94.128.43 54634 file.txt
4 131.94.128.43 54634 file.txt
confirm-accio
confirm-accio-again
Sending...
Done Sending
b'ERROR: No data expected until the accio command is issued!'
Here is the code:
import selectors
from socket import *
import sock
import sys
print(len(sys.argv), sys.argv[1], sys.argv[2], sys.argv[3])
host = sys.argv[1]
port = int(sys.argv[2])
file = sys.argv[3]
# Instaniating socket object
s = socket(AF_INET, SOCK_STREAM)
# Getting ip_address through host name
host_address = gethostbyname(host)
# Connecting through host's ip address and port number using socket object
s.connect((host_address, port))
print("confirm-accio\r\n")
print("confirm-accio-again\r\n")
fileToSend = open("file.txt", "rb")
print("Sending...")
while True:
data = fileToSend.read()
if not data:
break
s.send(data)
fileToSend.close()
s.send(b"Done")
print("Done Sending")
print(s.recv(1024))
s.close()

Downloading a file in a new directory- Socket Programming

I tried as hard is a could to create (or adapt) the following codes so that i can download a file (with any extension) from a server to the client in a new directory (to be more explicit, the client receives the file,downloads it in a new directory). I leave you the initial codes without my modifications,such in that way your changes won't be necessarly easier, but will help me where and why i'm wrong. Pay attention that codes are wrote in python and Linux OS(that's for directory paths). And do not forgot that i'm really new in Linux and Python. I tried many many variants but with many errors. Any help will be apreciated:).
**#CLIENT**
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 60000 # Reserve a port for your service.
s.connect((host, port))
s.send("Hello server!")
with open('received_file', 'wb') as f:
print 'file opened'
while True:
print('receiving data...')
data = s.recv(1024)
print('data=%s', (data))
if not data:
break
# write data to a file
f.write(data)
f.close()
print('Successfully get the file')
s.close()
print('connection closed')
**#SERVER**
import socket # Import socket module
port = 60000 # 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='mytext.txt'
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()

How to Send a file with keeping its extension through a python socket?

I'm trying to send one file which is txt file through a python socket. I want the txt file which is received by the client keeps its extension which is txt.
Here is my server's side:
import socket
port = 50000
s = socket.socket()
host = "localhost"
s.bind((host, port))
s.listen(5)
print 'Server listening....'
while True:
conn, addr = s.accept()
print 'Got connection from', addr
data = conn.recv(1024)
print('Server received', repr(data))
filename='file.txt'
f = open(filename,'rb')
while (f):
conn.send(filename)
f.close()
print('Done sending')
conn.close()
Here is my client's side:
import socket # Import socket module
s = socket.socket() # Create a socket object
host = "localhost" #Ip address that the TCPServer is there
port = 50000 # Reserve a port for your service every new transfer wants a new port or you must wait.
s.connect((host, port))
s.send("Hello server!")
while True:
print('receiving the file...')
data = s.recv()
if not data:
break
print('Successfully get the file')
s.close()
print('connection closed')
All I found online is either modifying this file or sending a text in that file.

Windows 10 - VB 5.2.4 with Ubuntu 16.04: Sending files between two VMs with Python

I'm new to python and this time I want to send a file between two VMs, first of all, the VMs are configured with NAT Network, both VMs can ping each other. The codes are the following:
Server side:
#server.py
import socket # Import socket module
port = 60000 # 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.bind(('', 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='runbonesi.py'
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.shutdown(socket.SHUT_WR)
print conn.recv(1024)
conn.close()
client side:
#client.py
import socket # Import socket module
s = socket.socket() # Create a socket object
#host = socket.gethostname() # Get local machine name
host = '10.0.2.15'
port = 60000 # Reserve a port for your service.
s.connect((host, port))
with open('received_file', 'wb') as f:
print 'file opened'
while True:
print('receiving data...')
data = s.recv(1024)
print('data=%s', (data))
if not data:
break
# write data to a file
f.write(data)
f.close()
print('Successfully get the file')
s.close()
print('connection closed')
The results can be seen in the following pictures:
Server side:
result on server
Client side:
result on client
The problem is, the client didn't receive the file as .py format, it only received as txt files. Please help me resolve this issue.
Thank you.
After s.connect((host, port)) in the client script you have to write s.send(...) with 'hello', for example. You also forgot to write the file extension '.py' in with open(...) (only if you want to save the file as Python script!). And you also have to add s.send(...) before you close the connection on the client side. ๐Ÿ˜‰

How can python socket client receive without being blocked

A simple demo of socket programming in python:
server.py
import socket
host = '127.0.0.1'
port = 8000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
while True:
data = conn.recv(1024)
print 'Received:', data
if not data:
break
conn.sendall(data)
print 'Sent:', data
conn.close()
client.py
import socket
host = '127.0.0.1'
port = 8000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.sendall('Hel')
s.sendall('lo world!')
print 'Received:', s.recv(1024)
s.close()
Now code work well. However, the client may not know if server will always send back every time. I tried symmetric code of while-loop in server.py
client_2.py
import socket
host = '127.0.0.1'
port = 8000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.sendall('Hel')
s.sendall('lo world!')
while True:
data = s.recv(1024)
if not data:
break
print 'Received:', data
s.close()
This code will block at
data = s.recv(1024)
But in server.py, if no data received, it will be blank string, and break from while-loop
Why it does not work for client? How can I do for same functionality without using timeout?
You can set a socket to non-blocking operation via socket.setblocking(false), which is equivalent to socket.settimeout(0). Solving this "without using timeout" is impossible.

Categories

Resources