When i try to get files from the server, i am getting the first file without a problem than getting this error on the second one; OSError: [WinError 10056] A connect request was made on an already connected socket
Client.py
files={
"file1":"10.10.10.10",
"files2":"10.10.10.15"
}
json={
"filename" : ""
}
while 1:
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
for file,ip in files:
json["filename"] = file
requestJSON = json.dumps(json)
socket.connect((ip, 3875))
socket.send(bytes(requestJSON, encoding='utf-8'))
with open("loc/" + file, 'w') as f:
while True:
print('receiving data...')
data = socket.recv(1024)
if not data:
break
f.write(data)
f.close()
socket.close()
Server.py
while 1:
conn, addr = socket.accept()
msg=conn.recv(1024)
file=json.loads(msg.decode('utf-8'))
fp = "/loc/" + file["filename"]
f = open(fp, 'rb')
d = f.read(1024)
while d:
clientSock.send(d)
l = f.read(1024)
f.close()
f = open(fp, 'rb')
d = f.read(1024)
while d:
clientSock.send(d)
l = f.read(1024)
f.close()
Should not be there d = f.read(1024) ?
Related
I have a client that let user to browse a file and upload to a server. Currently I'm just using command terminal to operate the program. When user type in fup in the terminal , the program will ask for filename and the file will be upload to the server if the filename input by user is valid.
So, what i want now is letting user to browse any file directory from a GUI without typing the filename to upload. I've tried to implement filedialog but it seem like not working, when i browse and upload a file, the server does not received any new file. I stucked with issues almost a week already but still couldn't find any solution, hope someone could help me. Thanks in advance
Client.py
import socket, sys, os
import time, shutil
# socket creating
def sock():
try:
s = socket.socket()
host = input('Enter Target IP :')
port = 9999
s.connect((host, port))
return (host, s)
except:
print("Error: In binding")
sock()
host, s = sock()
# upload file to client
def fup(conn):
try:
filename = input("\nMANO >>Filename? -> ")
if os.path.isfile(filename):
conn.send(str("fup~" + filename).encode("utf-8"))
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)
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:
print("Error")
# download file from client
def fdown(conn):
try:
print(os.getcwd())
filename = input("\nMANO >>Filename? -> ")
if filename != 'q':
conn.send(("fdown~" + filename).encode("utf-8"))
data = conn.recv(1024).decode("utf-8")
if data[:6] == 'EXISTS':
filesize = data[6:]
msg = input("File exists, " + str(filesize) + "Bytes, download? (Y/N)? -> ").upper()
if msg == 'Y':
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)
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()
else:
print("File Does Not Exist!")
except:
print("Error")
# commands that perform on client
def mano(cip, conn):
while True:
cli = input("MANO >>" + cip + ' >>')
if cli == 'fdown':
fdown(conn)
elif cli == 'fup':
fup(conn)
else:
print("Command not recognized")
mano(host, s)
Server.py
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()
Expected output:
since you are using a gui I think you should receive the inputs through the use of an tkinter.Entry widget not through the terminal with input()
Im doing a project where it connect to a server directory and read all their files.
So i just wrote a code to download the server files whenever i click on it. I can read small size file with no issues, but when i want to view a large content, only 1 line can be view and store to a list. Although i cant read all the large content, but im able to download it with no issues.
I can read and download all small size content with no issues:
The large file that i want to read from:
Output that i got when i read the large files. (Cant read all the content but i successfully to download the full content file)
CLIENT CODE:
def mouseHover(event):
x = lbox.curselection()[0]
file = lbox.get(x)
ext = (".txt", ".csv")
if file.endswith(ext):
self.s.send(("fdown~" + file).encode("utf-8")) #must have
data = self.s.recv(1024).decode("utf-8")
if data[:6] == 'EXISTS':
filesize = data[6:]
self.s.send("OK".encode("utf-8"))
f = open(file, 'wb') # must have
data = (self.s.recv(1024))
totalRecv = len(data)
f.write(data)
while int(totalRecv) < int(filesize):
data = self.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= data.splitlines()
print(data2)
self.text.delete('1.0', tk.END)
self.text.insert(tk.END, data)
else:
messagebox.showinfo("WARNING", "Currently only .txt/csv file is supported.")
lbox.bind("<<ListboxSelect>>", mouseHover)
SERVER CODE:
# 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)
break
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()
After you read each block of data, concatenate it to a string containing the whole file. Then at the end of the loop you can split this into lines and display it in the text box.
There's also no need to limit your recv() calls to 1000 bytes. Use filesize - totalRecv as the limit, and it will receive as much as is available, but not go past the end of the file.
There's no need to convert filesize to int every time through the loop, do it once when you assign the variable.
def mouseHover(event):
x = lbox.curselection()[0]
file = lbox.get(x)
ext = (".txt", ".csv")
if file.endswith(ext):
self.s.send(("fdown~" + file).encode("utf-8")) #must have
data = self.s.recv(1024).decode("utf-8")
if data[:6] == 'EXISTS':
filesize = int(data[6:])
self.s.send("OK".encode("utf-8"))
all_data = ''
with open(file, 'wb') as f: # must have
totalRecv = 0
while totalRecv < filesize:
data = self.s.recv(filesize - totalRecv)
totalRecv += len(data)
all_data += data
f.write(data)
sys.stdout.write("\r|" + "█" * int((totalRecv / filesize) * 50) + "|{0:.2f}".format(
(totalRecv / filesize) * 100) + "% ")
sys.stdout.flush()
time.sleep(0.01)
print("\nDownload Complete!")
global data2
data2= all_data.splitlines()
print(data2)
self.text.delete('1.0', tk.END)
self.text.insert(tk.END, all_data)
else:
messagebox.showinfo("WARNING", "Currently only .txt/csv file is supported.")
lbox.bind("<<ListboxSelect>>", mouseHover)
I'm trying to copy the folder from my server to the client the file is at the x directory.want to know how to set the file path in the server.
server side
filename = '/home/Desktop/features'
f = open(filename, 'rb')
while True:
l = f.read(buff_size)
while (l):
self.sock.sendall(l)
# print('Sent ',repr(l))
l = f.read(buff_size)
if not l:
f.close()
self.sock.close()
break
client side
with open('red_fi', 'rb') as f:
print('file opened client ')
time.sleep(3)
a = True
while a:
print('receiving data...')
data = s.recv(buff_size)
# print('data=%s', (data))
if not data:
f.close()
# time.sleep(3)
print('file closed client')
a = False
break
# write data to a file
f.write(data)
# time.sleep(2)
print('Successfully received the file')
print(id_list)
s.close()
I want the features folder to be copied from server to client.
i recently tried a tutorial on how to create a simple file server program with python. i don't know why everytime i check whether the file exists or not, it always tells me the file doesn't exist, here is the code
# server.py
import socket
import threading
import os
def RetFile(FileName, sock):
FileName = sock.recv(1024)
exists = os.path.isfile(FileName)
if exists:
sock.send(str.encode("EXISTS " + str(os.path.getsize(FileName))))
UserResponce = sock.recv(1024)
if UserResponce[: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(str.encode("ERR"))
sock.close()
def Main():
host = '127.0.0.1'
port = 5001
s = socket.socket()
s.bind((host, port))
s.listen(5)
print('Server Started')
while True:
conn, addr = s.accept()
print('Client Connected -> ', str(addr))
t = threading.Thread(target=RetFile, args=("retrThread", conn))
t.start()
if __name__ == '__main__':
Main()
# client.py
import socket
def Main():
host = '127.0.0.1'
port = 5001
s = socket.socket()
s.connect((host, port))
filename = input('File Name -> ')
if filename != 'q':
s.send(str.encode(filename))
data = s.recv(1024)
if data[:6] == "EXISTS ":
filesize = float(data[6:])
message = input('File Exists: ' + str(filesize) + ' Bytes, Download? (Y/N) -> ')
if message == 'Y':
s.send(str.encode("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:.2f}".format((totalRecv / float(filesize)) * 100) + "% Done!")
print('Download Complete')
else:
print("File Doesn't Exist")
s.close()
if __name__ == '__main__':
Main()
so where is the error of the code? the tutorial uses python 2.x and i use 3.x so i have some minor changes, and i'm new to this language so any help would be appreciated, thank you!
There were some issues in you code mostly related to byte conversion . you cannot send string on socket interface if you are using python 3 or above, with python 2 it works fine. So every message has to be changed to bytes before sending on socket i have fixed all such issues . Download is working fine
Fixed Server
# server.py
import socket
import threading
import os
def RetrFile(name, sock):
filename = sock.recv(1024)
if os.path.isfile(filename):
sock.send(b"Exist " + str(os.path.getsize(filename)).encode())
userResponse = sock.recv(1024)
if userResponse.decode() == 'OK':
with open(filename, 'rb') as f:
bytesToSend = f.read(1024)
while bytesToSend.decode() != "":
sock.send(bytesToSend)
bytesToSend = f.read(1024)
else:
sock.send(b"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=RetrFile, args=("retrThread", c))
t.start()
if __name__ == '__main__':
Main()
Fixed Client
# client.py
import socket
def Main():
host = '127.0.0.1'
port = 5000
s = socket.socket()
s.connect((host, port))
filename = bytearray(input("filename.. ").encode())
if filename != 'q':
s.send(filename)
data = s.recv(1024)
if data[:6].decode().rstrip().upper() == 'EXIST':
filesize = data[6:].decode().rstrip()
message = input("File exists, " + filesize+ "Bytes, download..? (Y/N)")
if message.upper() == 'Y':
totalRecv = 0
s.send(b'OK')
f = open('new_' + filename.decode(), 'wb')
data = s.recv(1024)
while data.decode() != "":
totalRecv += len(data)
data = s.recv(1024)
f.write(data)
print("{:2f}".format((totalRecv/float(filesize))*100)+ "Done")
print("Download complete")
else:
print("File doesn't exist")
if __name__ == '__main__':
Main()
Apart from the fact that a file may not exist, there is one obvious problem:
if data[:6] == "EXISTS ":
can never be True because data[:6] is a string of 6 characters, and "EXISTS " is 7 characters long.
I am trying this scenario:
Client sends file to server
Server updates on file and save it
Sends updated file back to client
Steps 1 and 2 are done correctly as I wanted but when client finishes sending the socket closes. I've tried this code but its not working. Any suggestions?
Client:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
H = socket.gethostname()
P = 1111
s.connect((H,P))
with open('File.txt', 'rb') as fileName:
for data in fileName:
s.sendall(data)
with open('ReFile.txt', 'wb') as File:
while True:
data = s.recv(1024)
print data
if not data:
break
File.write(data)
File.close()
Server:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
H= socket.gethostname()
P = 1111
s.bind((H, P))
s.listen(6)
c, address = s.accept()
print 'Connection with ' , address
with open('ReFile.txt', 'wb') as RecFile:
while True:
data = c.recv(1024)
print data
if not data:
break
RecFile.write(data)
RecFile.write("updated version")
RecFile.close()
with open('ReFile.txt', 'rb') as file:
for data in file:
s.sendall(data)
s.close()
Try this:
Server:
import socket
s = socket.socket()
H = socket.gethostname()
P = 1111
s.bind((H, P))
s.listen(6)
c, address = s.accept()
print 'Connection with ', address
lenF = int(c.recv(1024))
if lenF != 0:
c.sendall('Send data')
data = c.recv(lenF)
data += "\nUpdated Version"
RecFile = open('ReFile.txt','w')
RecFile.write(str(data))
RecFile.close()
fileN = open('ReFile.txt')
data = fileN.read(-1)
fileN.close()
lenF = len(data)
c.send(str(lenF))
if c.recv(5) == 'Ready':
c.send(data)
Here I am using lenF variable to get the size of file that I am getting from the client.
Client:
import socket
s = socket.socket()
H = socket.gethostname()
P = 1111
s.connect((H,P))
fileName = open('file.txt')
data = fileName.read(-1)
fileName.close()
dataL = int(len(data))
s.send(str(dataL))
validCheck = s.recv(9)
if validCheck == 'Send data':
print 'Sending file.......'
s.send(data)
dataL = int(s.recv(1024))
if dataL != 0:
s.send('Ready')
data = s.recv(dataL)
File = open('ReFile.txt','w')
File.write(data)
File.close()
Here I am using dataL variable to receive data length(file) and sending it.