Receive multiple files simultaneously - python

I wrote a script in Python 3.8.6 to send and receive files between different devices. I am sending and receiving files normally, the problem happens when I receive multiple simultaneous connections from different devices.
I configured the script to save the files in folders named with the address of the device that sends the file and what is happening is that when several devices send files at the same time, files from one device go to another folder, randomly. The files are mixed.
I have an idea of why it is happening but not how to solve it.
I thought as an alternative to receive only one connection at a time.
But I don't know how to do this.
sendfile.py
def conectividade(host="192.168.0.13", porta=1218, timeout=5):
while True:
try:
socket.setdefaulttimeout(timeout)
socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, porta))
return True
except Exception:
return False
# Function that sends the collected data.
def coleta():
total = []
conectividade()
conect = conectividade()
if conect == False:
print("\nConnectivity is",conect)
pass
else:
data_hoje = datetime.now().strftime('%Y-%b-%d')
direct = f".\\{data_hoje}\\"
arquivos = os.listdir(direct)
for arquivo in arquivos:
try:
sock = socket.socket()
host = "192.168.0.13"
porta = 1218
print("Connectivity is", conect)
sock.connect((host, porta))
total += arquivo.split(',')
sock.send(str.encode(arquivo))
arquivo = str.encode(direct + arquivo)
with open(arquivo, "rb") as file:
data = file.read(1024)
resposta = sock.recv(1024)
if resposta == b'Waiting file':
file_size = os.path.getsize(arquivo)
print(b"sending " + arquivo)
print(file_size,"kb")
sock.send(bytes(str(file_size),'utf-8'))
resposta = sock.recv(1024)
if resposta == b'Waiting...':
while data:
sock.send(data)
data = file.read(1024)
if not data:
print(f"**Sending Complete**\n")
sock.close()
# Delete files after uploads
if total == arquivos:
print(f"Uploaded files:\n",total)
except socket.error:
print("\nSocket Error\n")
receive.py
data_hoje = datetime.now().strftime('%Y-%b-%d')
sock = socket.socket()
host ='192.168.0.13'
porta = 1218
sock.bind((host, porta))
sock.listen(10)
total = []
while True:
conn, addr = sock.accept()
pasta = ".\\" + addr[0].replace('.','_')
subpasta = pasta + "\\" + data_hoje
if os.path.exists(pasta) == False:
os.makedirs(f'{pasta}')
if os.path.exists(subpasta) == False:
os.makedirs(f'{subpasta}')
data = conn.recv(1024)
while data == b'':
conn.close()
conn, addr = sock.accept()
data = conn.recv(1024)
if data == b'Finalizando socket':
print("Finalizando conexão com " + addr[0])
conn.close()
sock.close()
total += data.decode().split(',')
name_file = total[-1]
with open(f"{subpasta}\\{name_file}", "wb") as file:
conn.send(b"Waiting file")
data = conn.recv(1024)
tamanho = data.decode('utf-8')
file_size = int(tamanho)
if file_size != 0:
conn.send(b"Waiting...")
print("HOST <--> " + addr[0] + f" Download de {name_file} - {tamanho} kb")
while data:
data = conn.recv(1024)
file.write(data)
conn.close()

In receive.py you have:
conn, addr = sock.accept()
# [...]
while data == b'':
conn.close()
conn, addr = sock.accept()
data = conn.recv(1024)
The client that connects on the first accept() may be different from the client that connects on the accept() inside the cycle, which could lead to the files mixing up as you described. You should re-write it with a single accept(), to guarantee the whole processing is done for the same client. This approach is described in TCP/IP Client and Server - PyMOTW-3.
Modified receive.py:
data_hoje = datetime.now().strftime("%Y-%b-%d")
sock = socket.socket()
host = "192.168.0.13"
porta = 1218
sock.bind((host, porta))
sock.listen(10)
total = []
try:
while True:
conn, addr = sock.accept()
try:
pasta = ".\\" + addr[0].replace(".", "_")
subpasta = pasta + "\\" + data_hoje
if os.path.exists(pasta) is False:
os.makedirs(f"{pasta}")
if os.path.exists(subpasta) is False:
os.makedirs(f"{subpasta}")
data = b""
while data == b'':
data = conn.recv(1024)
if data == b"Finalizando socket":
print("Finalizando conexão com " + addr[0])
continue
total += data.decode().split(",")
name_file = total[-1]
with open(f"{subpasta}\\{name_file}", "wb") as file:
conn.send(b"Waiting file")
data = conn.recv(1024)
tamanho = data.decode("utf-8")
file_size = int(tamanho)
if file_size != 0:
conn.send(b"Waiting...")
print(
"HOST <--> " + addr[0] + f" Download de {name_file} - {tamanho} kb"
)
while data:
data = conn.recv(1024)
file.write(data)
finally:
conn.close()
finally:
sock.close()

Basically, what was causing the error was the conectividade() function recursively in the original script.
so I needed...
while True:
conn.close()
conn, addr = socket.accept()
data = conn.recv
What caused the files to mix, as said by fzdb ...
How was the new script ...
sendfile.py
import socket
import os
from datetime import datetime
def coleta():
total = []
data_hoje = datetime.now().strftime('%Y-%b-%d')
direct = f".\\{data_hoje}\\"
arquivos = os.listdir(direct)
for arquivo in arquivos:
try:
sock = socket.socket()
host = "192.168.0.13"
porta = 1218
print("Connectivity is",)# conect)
sock.connect((host, porta))
total += arquivo.split(',')
sock.send(str.encode(arquivo))
arquivo = str.encode(direct + arquivo)
with open(arquivo, "rb") as file:
data = file.read(1024)
resposta = sock.recv(1024)
if resposta == b'Waiting file':
file_size = os.path.getsize(arquivo)
print(b"sending " + arquivo)
print(file_size,"kb")
sock.send(bytes(str(file_size),'utf-8'))
resposta = sock.recv(1024)
if resposta == b'Waiting...':
while data:
sock.send(data)
data = file.read(1024)
if not data:
sock.close()
print(f"**Sending Complete**\n")
if total == arquivos:
print(f"Uploaded files:\n",total)
except socket.error:
print("\nSocket Error\n")
receive.py
import socket
import os
from datetime import datetime
data_hoje = datetime.now().strftime('%Y-%b-%d')
host ='192.168.0.13'
porta = 1218
sock.bind((host, porta))
sock.listen(10)
total = []
while True:
conn, addr = sock.accept()
pasta = ".\\" + addr[0].replace('.','_')
subpasta = pasta + "\\" + data_hoje
if os.path.exists(pasta) == False:
os.makedirs(f'{pasta}')
if os.path.exists(subpasta) == False:
os.makedirs(f'{subpasta}')
data = conn.recv(1024)
if data == b'':
conn.close()
total += data.decode().split(',')
name_file = total[-1]
try:
with open(f"{subpasta}\\{name_file}", "wb") as file:
conn.send(b"Waiting file")
data = conn.recv(1024)
tamanho = data.decode('utf-8')
file_size = int(tamanho)
if file_size != 0:
conn.send(b"Waiting...")
print("HOST <--> " + addr[0] + f" Download de {name_file} - {tamanho} bytes")
while data:
data = conn.recv(1024)
file.write(data)
except:
pass
Thank you!
For those who want to help with the original code ...
I have problems with NumPad on pynput
https://github.com/gconelhero/Keylogger

Related

Unable to upload files to server with socket connection (_pickle.UnpicklingError: invalid load key, 'E'.)

I'm using Python 3.7 and tkinter to develop this program. This program work as a file uploader to server through a socket connection. But the problem is when I upload a files it will show "upload completed" but the server didn't receive any of it. After the upload complete, an error will be show when I clicked on refresh button (the ListboxContentrefresh function is to refresh the listbox content of the server.) Does anyone know what I'm doing wrong here ? Thanks
Error message:
line 274, in ListboxContentrefresh
arr = pickle.loads(s.recv(1024))
_pickle.UnpicklingError: invalid load key, 'E'.
Image of my program:
Client code:
def ListboxContentrefresh():
#==========Listbox================
# THE ITEMS INSERTED WITH A LOOP
s.send(('flist~s').encode("utf-8"))
arr = pickle.loads(s.recv(1024))
listbox.delete(0, END) # clear listbox
for i in arr:
listbox.insert(END, i)
def mouseHover(event):
global x
x = listbox.curselection()[0]
file = listbox.get(x)
ext = (".txt", ".csv")
if file.endswith(ext):
s.send(("fdown~" + file).encode("utf-8")) # must have
data = s.recv(1024).decode("utf-8")
if data[:6] == 'EXISTS':
filesize = data[6:]
s.send("OK".encode("utf-8"))
f = open(file, 'wb') # must have
data = (s.recv(1024))
totalRecv = len(data)
f.write(data)
while int(totalRecv) < int(filesize):
data = s.recv(1024)
totalRecv += len(data)
f.write(data)
sys.stdout.write("\r|" + "█" * int((totalRecv / float(filesize)) * 50) + "|{0:.2f}".format(
(totalRecv / float(filesize)) * 100) + "% ")
sys.stdout.flush()
time.sleep(0.01)
print("\nDownload Complete!")
f.close()
global data2
data2 = open(file).read().splitlines()
joined_string = "\n".join(data2)
text.delete("1.0", END)
text.insert(END, joined_string)
else:
messagebox.showinfo("WARNING", "Currently only .txt/csv file is supported.")
listbox.bind("<<ListboxSelect>>", mouseHover)
def uploadfiletoserver():
try:
# open file selector
filename = filedialog.askopenfilename(parent=root, initialdir="/", title='Please select a directory')
if os.path.isfile(filename):
s.send(str("fup~" + filename).encode("utf-8"))
s.send(str.encode("EXISTS " + str(os.path.getsize(filename))))
filesize = int(os.path.getsize(filename))
userResponse = s.recv(1024).decode("utf-8")
if userResponse[:2] == 'OK':
with open(filename, 'rb') as f:
bytesToSend = f.read(1024)
s.send(bytesToSend)
totalSend = len(bytesToSend)
while int(totalSend) < int(filesize):
bytesToSend = f.read(1024)
totalSend += len(bytesToSend)
s.send(bytesToSend)
sys.stdout.write("\r|" + "█" * int((totalSend / float(filesize)) * 50) + "|{0:.2f}".format(
(totalSend / float(filesize)) * 100) + "% ")
sys.stdout.flush()
print("\nUpload Completed!")
else:
print("File Does Not Exist!")
except:
raise
Server code:
import socket, os, subprocess, shutil, pickle, struct, threading
## gettig the hostname by socket.gethostname() method
hostname = socket.gethostname()
## getting the IP address using socket.gethostbyname() method
ip_address = socket.gethostbyname(hostname)
# Create a Socket ( connect two computers)
def create_socket():
try:
global host
global port
global s
host = ""
port = 9999
s = socket.socket()
except socket.error as msg:
create_socket()
# Binding the socket and listening for connections
def bind_socket():
try:
global host
global port
global s
s.bind((host, port))
s.listen(5)
## printing the hostname and ip_address
print(f"Hostname: {hostname}")
print(f"IP Address: {ip_address}")
print(f"Running Port: {port}")
except socket.error as msg:
bind_socket()
print(bind_socket())
# send file list
def flist(conn):
try:
arr = pickle.dumps(os.listdir())
conn.send(arr)
print(arr)
except:
conn.send(('Error').encode("utf-8"))
# accept file from server
def fdown(filename, conn):
try:
data = conn.recv(1024).decode("utf-8")
if data[:6] == 'EXISTS':
filesize = data[6:]
conn.send("OK".encode("utf-8"))
f = open(filename, 'wb')
data = (conn.recv(1024))
totalRecv = len(data)
f.write(data)
while int(totalRecv) < int(filesize):
data = conn.recv(1024)
totalRecv += len(data)
f.write(data)
f.close()
except:
conn.send(('Error').encode("utf-8"))
# send file
def fup(filename, conn):
if os.path.isfile(filename):
conn.send(str.encode("EXISTS " + str(os.path.getsize(filename))))
filesize = int(os.path.getsize(filename))
userResponse = conn.recv(1024).decode("utf-8")
if userResponse[:2] == 'OK':
with open(filename, 'rb') as f:
bytesToSend = f.read(1024)
conn.send(bytesToSend)
totalSend = len(bytesToSend)
while int(totalSend) < int(filesize):
bytesToSend = f.read(1024)
totalSend += len(bytesToSend)
conn.send(bytesToSend)
else:
conn.send("ERROR".encode("utf-8"))
# main
def main(s):
while True:
data = (s.recv(1024)).decode("utf-8").split('~')
if data[0] == 'fdown':
fup(data[1], s)
elif data[0] == 'fup':
fdown(data[1], s)
elif data[0] == 'flist':
flist(s)
else:
s.send(".".encode('utf-8'))
def socket_accept():
while True:
conn, address = s.accept()
t = threading.Thread(target=main, args=(conn,))
t.start()
create_socket()
bind_socket()
socket_accept()
It looks like there's probably an error in your flist function. Try changing the client to:
def ListboxContentrefresh():
#==========Listbox================
# THE ITEMS INSERTED WITH A LOOP
s.send(('flist~s').encode("utf-8"))
arr = s.recv(1024)
if arr == b'Error':
messagebox.showinfo("ERROR", "Error received from flist!")
return
arr = pickle.loads(arr)
...
This should show you if there is an error on the client-side. And if you'd like you can change the server-side to help diagnose the issue:
def flist(conn):
try:
arr = pickle.dumps(os.listdir())
conn.send(arr)
print(arr)
except Exception as e:
conn.send(('Error').encode("utf-8"))
print("Exception: ", e)

How to make a socket server run forever without closed itself (Python)

Whenever the client disconnect, the server will close itself. How can i make the server to run forever ?
What i'm doing
The server let one client to retrieve files with no issues. But the problem is when the client close the program, the server will also closed itself and wouldn't let another client to establish the connection . I had read a few articles about using while loops to make the session alive. Does anyone know how can I do that ?
Server.py
import socket, os, subprocess, shutil, pickle, struct
# Create a Socket ( connect two computers)
def create_socket():
try:
global host
global port
global s
host = ""
port = 9999
s = socket.socket()
except socket.error as msg:
create_socket()
# Binding the socket and listening for connections
def bind_socket():
try:
global host
global port
global s
s.bind((host, port))
s.listen(5)
except socket.error as msg:
bind_socket()
# send file list
def flist(conn):
try:
arr = pickle.dumps(os.listdir())
conn.send(arr)
except:
conn.send(('Error').encode("utf-8"))
# accept file from server
def fdown(filename, conn):
try:
data = conn.recv(1024).decode("utf-8")
if data[:6] == 'EXISTS':
filesize = data[6:]
conn.send("OK".encode("utf-8"))
f = open(filename, 'wb')
data = (conn.recv(1024))
totalRecv = len(data)
f.write(data)
while int(totalRecv) < int(filesize):
data = conn.recv(1024)
totalRecv += len(data)
f.write(data)
f.close()
except:
conn.send(('Error').encode("utf-8"))
# send file
def fup(filename, conn):
if os.path.isfile(filename):
conn.send(str.encode("EXISTS " + str(os.path.getsize(filename))))
filesize = int(os.path.getsize(filename))
userResponse = conn.recv(1024).decode("utf-8")
if userResponse[:2] == 'OK':
with open(filename, 'rb') as f:
bytesToSend = f.read(1024)
conn.send(bytesToSend)
totalSend = len(bytesToSend)
while int(totalSend) < int(filesize):
bytesToSend = f.read(1024)
totalSend += len(bytesToSend)
conn.send(bytesToSend)
else:
conn.send("ERROR".encode("utf-8"))
# main
def main(s):
while True:
data = (s.recv(1024)).decode("utf-8").split('~')
if data[0] == 'fdown':
fup(data[1], s)
elif data[0] == 'fup':
fdown(data[1], s)
elif data[0] == 'flist':
flist(s)
else:
s.send(".".encode('utf-8'))
# Establish connection with a client (socket must be listening)
def socket_accept():
conn, address = s.accept()
main(conn)
conn.close()
create_socket()
bind_socket()
socket_accept()
You should put accept in the loop, and you may need use a thread to handle read
sample code:
def handle_read(s):
while True:
data = s.recv(1024)
if not data:
#When the client closed, recv will return an empty data
s.close()
break
data = data.decode("utf-8").split('~')
if data[0] == 'fdown':
fup(data[1], s)
elif data[0] == 'fup':
fdown(data[1], s)
elif data[0] == 'flist':
flist(s)
else:
s.send(".".encode('utf-8'))
def socket_accept():
while True:
conn, address = s.accept()
t = threading.Thread(target = handle_read, args=(conn, ))
t.start()

python 3 sending a file through a socket

I'm trying to send files from server to client with the code here and doesn't succeed, the client gets stuck on the last recv. Server is done sending all the times. I've tried many things to try to solve:
sending 'STOP' when server is done sending -> client somehow receives the last bytes with 'STOP' and writes it to the file(even though they were different client.send() the client mixed it)
Sending how many bytes am I going to receive and then sending the bytes
Sending a pickle of [bytes, 'OK'/'STOP']
Server.py
host = '0.0.0.0'
port = 9898
s = socket.socket()
s.bind((host, port))
s.listen(1)
client, addr = s.accept()
def download_file(self, file_name, client):
with open(file_name, 'rb') as f:
file_name_without_path = file_name.split('\\')
file_name_without_path = file_name_without_path[len(file_name_without_path) - 1]
filesize = os.path.getsize(file_name)
client.send(pickle.dumps([file_name_without_path, filesize])) # send name and size of file
bytesToSend = f.read(1024)
client.send(bytesToSend)
print(bytesToSend)
bytes_sent = 0
while len(bytesToSend) != 0:
bytesToSend = f.read(1024)
bytes_sent += len(bytesToSend)
client.send(bytesToSend)
print(bytesToSend)
print('done')
Client.py
s = socket()
PORT = 9898
s.connect(('127.0.0.1', PORT))
def download(self, path):
filename, filesize = pickle.loads(s.recv(1024))
new_file_path = path + '\\' + filename
f = open(new_file_path, 'wb')
data = s.recv(1024)
totalRecv = len(data)
f.write(data)
while data != ''.encode():
print('before')
data = s.recv(1024)
print(data)
print('after')
totalRecv += len(data)
percetage = (totalRecv / filesize) * 100
print(str((totalRecv / filesize) * 100) + "%")
f.write(data)
if percetage >= 100:
break
f.close()
print('done')

Type Error using Socket communication even while decoding to byte string

Hello I got a problem with a type error I cant get rid off.
I have build a server named processA.py and a client processB.py
I start the server calling processA and it starts up
I start the client calling processB and it starts up
Now I input the name of the file I want to send over a socket.
The image must be in the same folder as the programms.
You can use the sample code from below for reproducing the error.
I choose: lena.jpg
I get an error in line 15, in of my processA.py:
sock.send("EXISTS" + str(os.path.getsize(filenameByte))) TypeError: a
bytes-like object is required, not 'str'
processA.py
'''
Created on 29 Nov 2017
#author: Poor Student
'''
import numpy
import socket
import threading
import os
def RtrFile(name, sock):
filenameByte = sock.recv(1024)
filenameStr = filenameByte.decode('ascii')
if os.path.isfile(filenameStr):
sock.send("EXISTS" + str(os.path.getsize(filenameByte)))
userResponse = sock.recv(1024)
if userResponse[:2] == 'OK':
with open(filenameByte, 'rb') as f:
bytesToSend = f.read(1024)
sock.send(bytesToSend)
while bytesToSend != "":
bytesToSend = f.read(1024)
sock.send(bytesToSend)
else:
sock.send("ERR")
sock.close()
def Main():
host = "127.0.0.1"
port = 5000
s = socket.socket()
s.bind((host,port))
s.listen(5)
print("server started.")
while True:
c, addr =s.accept()
print("client connected ip:< " + str(addr) +">")
t = threading.Thread(target = RtrFile, args=("rtrThread",c))
t.start()
s.close()
if __name__ == "__main__":
Main()
processB.py
'''
Created on 29 Nov 2017
#author: Poor Student
'''
import socket
def Main():
host = "127.0.0.1"
port = 5000
s = socket.socket()
s.connect((host,port))
filename = input("Filename? -> ")
if filename != "q":
s.send(filename.encode())
data = s.recv(1024)
if data[:6] == "EXISTS":
filesize = int(data[6:])
message = 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)
totalRecv = len(data)
f.write(data)
while totalRecv < filesize:
data = s.recv(1024)
totalRecv += len(data)
f.write(data)
print("(0:.f)".format((totalRecv)/float(filesize))*100 +"done")
print("Download Complete")
else:
print("File does not exists")#
s.close()
if __name__ == "__main__":
Main()
I found an answer. In python 3 you have allways convert your Strings to byte strings when sending them. After sending them to the receiver you have to decode them again and this must be done for the hole communication which is why the error allways shows up in the same module.
Process A:
'''
Created on 29 Nov 2017
#author: Happy student
'''
import numpy
import socket
import threading
import os
from idlelib.IOBinding import encoding
def RtrFile(name, sock):
filenameByte = sock.recv(1024)
filenameStr = filenameByte.decode('ascii')
print("FilenameStr",filenameStr)
if os.path.isfile(filenameStr):
print("Type:",type(filenameByte))
print(os.path.getsize(filenameByte))#
sendStr = "EXISTS" + str(os.path.getsize(filenameByte))
#Convert the string to byte because otherwise it will not be send
sock.send((sendStr.encode(encoding)))
userResponse = sock.recv(1024)
#the Responce will be received in byte and will be converted to a string to make it checkable
userResponceStr = userResponse.decode('ascii')
if userResponceStr[:2] == 'OK':
with open(filenameByte, 'rb') as f:
bytesToSend = f.read(1024)
sock.send(bytesToSend)
while bytesToSend != "":
bytesToSend = f.read(1024)
sock.send(bytesToSend)
else:
print("User response not known")
else:
sendStr = "ERR"
sock.send(sendStr.encode(encoding))
sock.close()
def Main():
host = "127.0.0.1"
port = 5000
s = socket.socket()
s.bind((host,port))
s.listen(5)
print("server started.")
while True:
c, addr =s.accept()
print("client connected ip:< " + str(addr) +">")
t = threading.Thread(target = RtrFile, args=("rtrThread",c))
t.start()
s.close()
if __name__ == "__main__":
Main()
processB.py
'''
Created on 29 Nov 2017
#author: Happy student
'''
import socket
from idlelib.IOBinding import encoding
def Main():
host = "127.0.0.1"
port = 5000
s = socket.socket()
s.connect((host,port))
filename = input("Filename? -> ")
if filename != "q":
s.send(filename.encode())
data = s.recv(1024)
dataStr = data.decode('ascii')
if dataStr[:6] == "EXISTS":
filesize = int(dataStr[6:])
message = input("File Exists, " +str(filesize) + "Bytes, download? (Y/N)? ->")
if message == "Y" or message =="y":
sendStr = "OK"
s.send(sendStr.encode(encoding))
#create new file new_filename and
f = open("new_" + filename, "wb")
data = s.recv(1024)
totalRecv = len(data)
f.write(data)
while totalRecv < filesize:
data = s.recv(1024)
totalRecv += len(data)
f.write(data)
print("Download Complete")
else:
print(message +"was not noticed")
exit()
else:
print("File does not exists")#
s.close()
if __name__ == "__main__":
Main()

print contents of file - python socket

I'm trying to print the contents of a file to the client using the defined command 'get'. I am not getting the contents of the file instead the contents are getting over written with Server Says... get test.txt.
Here is my client code:
import socket
import sys
import os
HOST = 'localhost'
PORT = 8082
size = 1024
def ls():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT))
s.send(userInput)
result = s.recv(size)
print result
s.close()
return
def put(commandName):
socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket1.connect((HOST, PORT))
socket1.send(commandName)
string = commandName.split(' ', 1)
inputFile = string[1]
with open(inputFile, 'rb') as file_to_send:
for data in file_to_send:
socket1.sendall(data)
print 'PUT Successful'
socket1.close()
return
def get(commandName):
socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket1.connect((HOST, PORT))
socket1.send(commandName)
string = commandName.split(' ', 1)
inputFile = string[1]
with open(inputFile, 'wb') as file_to_write:
while True:
data = socket1.recv(1024)
print data
if not data:
break
print data
file_to_write.write(data)
file_to_write.close()
print 'GET Successful'
#socket1.close()
return
done = False
while not done:
userInput = raw_input()
if "quit" == userInput:
done = True
elif "ls" == userInput:
ls()
else:
string = userInput.split(' ', 1)
if (string[0] == 'put'):
put(userInput)
elif (string[0] == 'get'):
get(userInput)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT))
s.send(userInput)
data = s.recv(size)
s.close()
print 'Received:', data
And server code:
import socket
import os
import sys
host = ''
port = 8082
backlog = 5
size = 1024
serverID = socket.gethostbyname(socket.gethostname())
info = 'SERVER ID: {} port: {}'.format(serverID, port)
print info
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(backlog)
done = False
# Loop until client sends 'quit' to server
while not done:
client, address = s.accept()
data = client.recv(size)
print "Server received: ", data
if data:
client.send("Server Says... " + data)
if data == "quit":
done = True
elif data == "ls":
data = os.listdir("C://")
client.send(data[0])
else:
string = data.split(' ', 1)
dataFile = string[1]
if (string[0] == 'put'):
with open(dataFile, 'wb') as file_to_write:
while True:
data = client.recv(1024)
if not data:
break
file_to_write.write(data)
file_to_write.close()
break
print 'Receive Successful'
elif (string[0] == 'get'):
with open(dataFile, 'rb') as file_to_send:
for data in file_to_send:
client.send(data)
print 'Send Successful'
client.close()
s.close()
print "Server exiting."
You are getting the content of the file but it is empty... and your code works just because you probably run it in the same directory.
Your client open file to write (and then it is empty) and the server reads it (both code use the same file name). You probably wanted to read file from C:\ so you should change server code and replace line:
with open(dataFile, 'rb') as file_to_send:
with:
with open('C:\\' + dataFile, 'rb') as file_to_send:
No matter what you send to the server this condition is true so you get "server says..."
if data:
client.send("Server Says... " + data)
You have also several flaws in you client I think. Like your commands are sent 2 times: once in the client 'main' when you do:
s.send(userInput)
And once in the functions like get and ls :
socket1.send(commandName)

Categories

Resources