Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 file doesn't exist
#1
I am trying to display an image through socket programming,
I have a server and a client file, and they seem to run fine,
however, once I write my file in the console (see input command),
I always obtain the message 'file doesn't exist'.
I am not sure why, because the files I use are in the same directory as
the python files.
Any ideas?
#SERVER
import socket
import threading
import os

from idlelib.iomenu import encoding


def retrieve_file(name, sock):
    filename=sock.recv(1024)
    if os.path.isfile(filename):
        sock.send( ("EXISTS" + str(os.path.getsize(filename))).encode(encoding) )
        user_response = sock.recv(1024)
        if user_response[:2] == 'OK':
            with open(filename, 'rb') as f:
                send_bytes=f.read(1024)
                sock.send(send_bytes)
                while send_bytes !='':
                    send_bytes= f.read(1024)
                    sock.send(send_bytes)
    else:
        sock.send(b"error, file does not exist")
    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=retrieve_file, args=("retrThread",c))
        t.start()

    s.close()

if __name__ == '__main__':
    Main()

#CLIENT

import socket

def Main():
    host = "127.0.0.1"
    port = 5000

    s=socket.socket()
    s.connect((host,port))


    filename= input("enter file name ->")
    if filename != 'q':
        s.send(filename.encode())
        data= s.recv(1024)
        if data[:6] == 'EXISTS':
            filesize = int(data[:6])
            message= input("this file exists " + str(filesize) + "bytes, download(Y/N)?")
            if message == 'Y':
                s.send('OK')
                f=open(filesize, 'wb')
                data=s.recv(1024)
                total_received=len(data)
                f.write(data)
                while total_received < filesize:
                    data=s.recv(1024)
                    total_received += len(data)
                    f.write(data)
                print("download complete")

        else:
            print("file doesn't exist")
    s.close()


if __name__ == '__main__':
    Main()

Quote
#2
Quote:I always obtain the message 'file doesn't exist'.
Always show the entire error traceback, verbatim

Quote:I am not sure why, because the files I use are in the same directory as
the python files
The current working directory may not be the same as the src directory, to assure this is the case, add the following statement as the first line executed:
# add import
import os

#add as first line executed (in front of line 6)
os.chdir(os.path.abspath(os.path.dirname(__file__)))

Quote
#3
I did what you said, by adding that line,
but I still get the same outcome.

this is the server output
Output:
C:\Users\\PycharmProjects\client-server\venv\Scripts\python.exe C:/Users//PycharmProjects/client-server/server_2.py server started... client connected ip>:('127.0.0.1', 59653)
and this is the client output
Output:
C:\Users\PycharmProjects\client-server\venv\Scripts\python.exe C:/Users/PycharmProjects/client-server/client_2.py enter file name ->upper.txt file doesn't exist Process finished with exit code 0
Quote
#4
Try to get more information, replace print("file doesn't exist") with
print("file doesn't exist, got:", repr(data))
Quote
#5
this is the outcome that I have now, but I am not sure what this means.

Output:
C:\Users\PycharmProjects\client-server\venv\Scripts\python.exe C:/Users/PycharmProjects/client-server/client_2.py enter file name ->upper.txt file doesn't exist, got: b'EXISTS18' Process finished with exit code 0
Quote
#6
data is byte string
you need to compare it with b'EXISTS' on line 17:
if data[:6] == b'EXISTS':
or decode data:
if data[:6].decode() == 'EXISTS':
also as per PEP8 it's better to use startswith:
if data.decode().startswith('EXISTS'):
Quote
#7
I changed line 16 and got this error.
Also, what do you mean by PEP8 ?
which line are you referring to?

Error:
enter file name ->upper.txt Traceback (most recent call last): File "C:/Users/PycharmProjects/client-server/client_2.py", line 36, in <module> Main() File "C:/Users/PycharmProjects/client-server/client_2.py", line 16, in Main filesize = int(data[:6]) ValueError: invalid literal for int() with base 10: b'EXISTS' Process finished with exit code 1
Quote
#8
(Oct-24-2019, 08:46 AM)mcgrim Wrote: I changed line 16 and got this error.
why would you change it?

(Oct-24-2019, 08:46 AM)mcgrim Wrote: which line are you referring to?
As i said - line 17, in CLIENT code. Currently it reads:
        if data[:6] == 'EXISTS':
(Oct-24-2019, 08:46 AM)mcgrim Wrote: Also, what do you mean by PEP8 ?

https://www.python.org/dev/peps/pep-0008...mendations
PEP8 Wrote:Use ''.startswith() and ''.endswith() instead of string slicing to check for prefixes or suffixes.

startswith() and endswith() are cleaner and less error prone:
Yes: if foo.startswith('bar'):
No:  if foo[:3] == 'bar':
Quote
#9
I meant line 17 before,
however, I changed that line from
if data[:6] == 'EXISTS':
to
if data.decode().startswith('EXISTS'):
and got this error
Error:
enter file name ->upper.txt Traceback (most recent call last): File "C:/Users//PycharmProjects/client-server/client_2.py", line 37, in <module> Main() File "C:/Users//PycharmProjects/client-server/client_2.py", line 17, in Main filesize = int(data[:6]).encode() ValueError: invalid literal for int() with base 10: b'EXISTS' Process finished with exit code 1
Quote
#10
obviously first 6 chars are EXISTS, so how you expect it to be int?
replace
        data= s.recv(1024)
        if data[:6] == 'EXISTS':
            filesize = int(data[:6])
with
data= s.recv(1024)
data = data.decode()
if data.startswith('EXISTS'):
    filesize = int(data[6:])
or

data= s.recv(1024)
if data.startswith(b'EXISTS'):
    filesize = int(data[6:])
Gribouillis likes this post
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  HTML file uploaded through python screen doesn't look as expected miker2808 6 1,016 Aug-04-2018, 02:05 AM
Last Post: Larz60+

Forum Jump:


Users browsing this thread: 1 Guest(s)