Trying to create a crude send/receive through TCP in python - python

So far I can send files to my "fileserver" and retrieve files from there as well. But i can't do both at the same time. I have to comment out one of the other threads for them to work. As you will see in my code.
SERVER CODE
from socket import *
import threading
import os
# Send file function
def SendFile (name, sock):
filename = sock.recv(1024)
if os.path.isfile(filename):
sock.send("EXISTS " + str(os.path.getsize(filename)))
userResponse = sock.recv(1024)
if userResponse[:2] == 'OK':
with open(filename, 'rb') as f:
bytesToSend = f.read(1024)
sock.send(bytesToSend)
while bytesToSend != "":
bytesToSend = f.read(1024)
sock.send(bytesToSend)
else:
sock.send('ERROR')
sock.close()
def RetrFile (name, sock):
filename = sock.recv(1024)
data = sock.recv(1024)
if data[:6] == 'EXISTS':
filesize = long(data[6:])
sock.send('OK')
f = open('new_' + filename, 'wb')
data = sock.recv(1024)
totalRecieved = len(data)
f.write(data)
while totalRecieved < filesize:
data = sock.recv(1024)
totalRecieved += len(data)
f.write(data)
sock.close()
myHost = ''
myPort = 7005
s = socket(AF_INET, SOCK_STREAM)
s.bind((myHost, myPort))
s.listen(5)
print("Server Started.")
while True:
connection, address = s.accept()
print("Client Connection at:", address)
# u = threading.Thread(target=RetrFile, args=("retrThread", connection))
t = threading.Thread(target=SendFile, args=("sendThread", connection))
# u.start()
t.start()
s.close()
CLIENT CODE
from socket import *
import sys
import os
servHost = ''
servPort = 7005
s = socket(AF_INET, SOCK_STREAM)
s.connect((servHost, servPort))
decision = raw_input("do you want to send or retrieve a file?(send/retrieve): ")
if decision == "retrieve" or decision == "Retrieve":
filename = raw_input("Filename of file you want to retrieve from server: ") # ask user for filename
if filename != "q":
s.send(filename)
data = s.recv(1024)
if data[:6] == 'EXISTS':
filesize = long(data[6:])
message = raw_input("File Exists, " + str(filesize)+"Bytes, download?: Y/N -> ")
if message == "Y" or message == "y":
s.send('OK')
f = open('new_' + filename, 'wb')
data = s.recv(1024)
totalRecieved = len(data)
f.write(data)
while totalRecieved < filesize:
data = s.recv(1024)
totalRecieved += len(data)
f.write(data)
print("{0: .2f}".format((totalRecieved/float(filesize))*100)) + "% Done" # print % of download progress
print("Download Done!")
else:
print("File does not exist!")
s.close()
elif decision == "send" or decision == "Send":
filename = raw_input("Filename of file you want to send to server: ")
if filename != "q":
s.send(filename)
if os.path.isfile(filename):
s.send("EXISTS " + str(os.path.getsize(filename)))
userResponse = s.recv(1024)
if userResponse[:2] == 'OK':
with open(filename, 'rb') as f:
bytesToSend = f.read(1024)
s.send(bytesToSend)
while bytesToSend != "":
bytesToSend = f.read(1024)
s.send(bytesToSend)
else:
s.send('ERROR')
s.close()
s.close()
I'm still new to programming, so this is quite tough for me. All in all i'm just trying to figure out how to send AND receive files without having to comment out the bottom threads in my SERVER CODE.
Please and thank you!

On the serverside, you're trying to use the same connection for your two threads t and u.
I think it might work if you listened for another connection in your while True: loop on the server, after you started your first thread.
I always use the more high-level socketserver module (Python Doc on socketserver), which also natively supports Threading. I recommend checking it out!
By the way, since you do a lot of if (x == 'r' or x == 'R'): you could just do if x.lower() == 'r'

just made an if statement sending a True or False and that will decide which thread to execute.

Related

Server's Data is not getting received by Client in Python Socket

I am trying to create a function that allows the client to download a file from the server. Below oare the relevant portions of the code. I have gotten to the point where a text file with the same name is created in the client folder, but it is just empty with no data. The programs get to the "received file line" but nothin else.
Client Code:
elif cmd == "DOWN":
filename = data[1]
print(filename)
client.send(filename.encode(FORMAT))
f = open("client/" + filename, 'wb')
while True:
print("receiving data")
data = client.recv(1024).decode(FORMAT)
if not data:
break
f.write(data)
print("Data: %s", (data))
f.close()
Server Code:
elif cmd == "DOWN":
file = conn.recv(1024).decode(FORMAT)
f = open("server/"+file, 'rb')
l = f.read(1024)
while (l):
conn.send(l.encode(FORMAT))
print("send data", repr(1))
l = f.read(1024)
f.close()
print("done sending")
Output:
Welcome to the server
> DOWN abc.txt
abc.txt
recieving data
The program enters the loop to receive the data, but nothing else. Any help would be appreciated. Thank you.

Python TCP server/client for transferring files

I was trying to make a TCP server/client in order to transfer files between the two. My code looks like this (its messy) for now. When sending a GET command I want to receive a file from the server which works but only if I ^C to close the client (the file is created but nothing is written in it until I close the client). When I send a SEND command to get a file from the server (machine running the server) it works but just because I shutdown the socket after that. I want to keep the socket connected after sending the file.
Here is the code that is used for this:
server.py
elif msg[:4] == 'file':
client_command = msg[5:9]
if client_command == 'GET ':
file_name = msg[9:]
f = open(file_name, "rb")
l = f.read(self.BUFF_SIZE)
while(l):
self.send_info(l)
l = f.read(self.BUFF_SIZE)
f.close()
elif client_command == 'SEND':
file_name = msg[10:]
f = open(file_name, "wb")
l = self.recv_info()
while(l):
f.write(l)
l = self.recv_info()
f.close()
def send_info(self, msg):
info = bytes(msg)
send = self.client_socket.sendall(info)
return send
def recv_info(self):
recv = self.client_socket.recv(self.BUFF_SIZE)
return recv
client.py
answer = input()
elif answer[:4] == 'file':
s.send(answer.encode('iso-8859-1'))
command = answer[5:9]
if command == 'GET ':
fileName = answer[9:]
f = open(fileName, 'wb')
l = s.recv(2048)
while(l):
f.write(l)
l = s.recv(2048)
f.close()
elif command == 'SEND':
fileName = answer[10:]
f = open(fileName, 'rb')
l = f.read(2048)
while (l):
s.send(l)
l = f.read(2048)
f.close()
s.shutdown(socket.SHUT_WR)
I will change the way I'm taking care of the filename and move away from slicing once I'm sure the transferring works.
I probably just don't understand how the transfer should be made but if anyone could correct my code or explain how it should be tin order to be functional. I just want to be able to send and transfer files without the socket closing (shutdown) so that I don't have to reconnect the client after every command and without having to close the client to finish transferring a file. I can add more of the code if need be.
Thanks for any help.
The problem might be the file is being buffered. If you want to enforce the file will be written right after you have received, you can use the flush method:
f = open(fileName, 'wb')
l = s.recv(2048)
while(l):
f.write(l)
l = s.recv(2048)
f.flush()
f.close()
Note: I Highly suggest you use the with statement, to ensure the file is always closed:
with open(filename, 'wb') as f:
l = s.recv(2048)
while(l):
f.write(l)
l = s.recv(2048)
f.flush()

Python sockets: sending UTF-8 with sockets

I'm trying to send a JSON File from a server to a client. The problem is, in the JSON File there is a special char 'Ć' and when i recieve the file in the client it's written 'F'.
I'm not sure if i have to decode/encode it.
Here is the server:
import socket
sourcefile = 'TMS.JSON'
TCP_IP = '10.0.9.6' #IP of server!
TCP_PORT = 3487
s = socket.socket()
s.bind((TCP_IP, TCP_PORT))
s.listen(5)
print('DEBUG: Server listening....')
while True:
conn, addr = s.accept()
print('DEGUG: Got connection from', addr)
f = open(sourcefile, 'rb')
l = f.read(1024)
while (l):
conn.send(l)
l = f.read(1024)
f.close()
print('DEGUG: Done sending')
conn.close()
Here is the client:
import socket
import json
destinationfile = 'TMS_recieved.JSON'
TCP_IP = '10.0.9.6' #IP of server!
TCP_PORT = 3487
s = socket.socket()
s.connect((TCP_IP, TCP_PORT))
print('DEBUG: Recieving data....')
with open(destinationfile, 'wb') as f: #create JSON FILE
while True:
data = s.recv(1024)
if not data:
break
f.write(data)
f.close()
print('DEBUG: Successfully get the file')
s.close()
print('DEBUG: Connection closed')
with open(destinationfile, 'r') as f: #read JSON FILE
datastore = json.load(f)
print()
print('datastore['name'])
Can please someone help me?
Thanks
At client.py replace
with open(destinationfile, 'r') as f:
datastore = json.load(f)
with
with open(destinationfile, 'rb') as f:
datastore = f.read().decode('UTF-8')
datastore = json.loads(datastore)
And then it works for me if TMS.JSON is
{"name": "Ć"}
Output:
DEBUG: Recieving data....
DEBUG: Successfully get the file
DEBUG: Connection closed
Ć

transfer Encrypted File by python : InvalidToken error

I want to send a file with a simple socket program in python.
Receiver :
import socket
import sys
from cryptography.fernet import Fernet
s = socket.socket()
s.bind(("0.0.0.0",9999))
s.listen(10)
i = 1
while True:
sc, address = s.accept()
print(address)
f = open('file_'+ str(i),'wb')
i=i+1
fi = Fernet(b'RkmYkE0W0oirK7e-aq7cfRGaq0nnn_GSvLIbLZHfpfw=sssdsdds')
while (True):
l = fi.decrypt(sc.recv(1024))
f.write(l)
if not l:
break
f.close()
sc.close()
print('copied the file.')
sender:
from cryptography.fernet import Fernet
message = "my deep dark secret".encode()
#key = Fernet.generate_key()
fi = Fernet(b'RkmYkE0W0oirK7e-aq7cfRGaq0nnn_GSvLIbLZHfpfw=sssdsdds')
encrypted = fi.encrypt(message)
#print(key)
print(encrypted)
decrypted = fi.decrypt(encrypted)
print(decrypted.decode("utf-8"))
s = socket.socket()
s.connect(("192.168.1.141", 9999))
f = open("l.pdf", "rb")
l = fi.encrypt(f.read(1024))
while (l):
s.send(l)
l = f.read(1024)
s.close()
but I have faced this error:
cryptography.fernet.InvalidToken
raise Invalid Signature("Signature did not match digest.")
What should I do to decrypt my file? I have tested this transfer by a PDF file.

How to save a received file from client server with different name using Python

I have a server which accepts a file from each of his client but I would like to save each file in ascending order like file1.txt file2.txt.. etc
My server part that accepts the file is
def getfile(self):
count = count+1
g = open('from_client'+count+'.txt','wb')
while True:
print('receiving data...')
data = self.sock.recv(BUFFER_SIZE)
print('data=%s', (data))
if not data:
g.close()
print('Successfully get the file')
self.sock.close()
break
# write data to a file
g.write(data)
How to save it each time with different filename?
I had to convert my counter to string with str(count) and place count=0 outside my class
def getfile(self,count):
count = count+1
g = open('from_client'+str(count)+'.txt','wb')
while True:
print('receiving data...')
data = self.sock.recv(BUFFER_SIZE)
print('data=%s', (data))
if not data:
g.close()
print('Successfully get the file')
self.sock.close()
break

Categories

Resources