What Happened on Tcp When Uploading a File





I'm looking to find some assistance in my python socket programming.

Objective: upload a file from the Client to the Server. My current setup involves two virtual machines, a Server and a Client, where the respective .py files will reside; server.py and customer.py . The issues I'yard experiencing is, that when I go to cull the upload option, the output reads "File uploading.... File successfully uploaded" Only when I expect on the server side, the file doesn't exist - nor do I receive an error. The server shows that information technology received a connectedness when I ship the file to upload. What I have currently is beneath... Any assist would exist profoundly appreciated.

Server.py

                  import config, protocol
import os
from socket import *
import threading
import time
import sys

form server():

# Constructor: load the server information from config file
def __init__(cocky):
self.port, self.path, self.path2 = config.config().readServerConfig()

# office to receive file information from client
def receiveFile(self, serverSocket, fileName):
serverSocket.connect()
serverSocket.send(protocol.prepareMsg(protocol.HEAD_UPLOAD, fileName))
with open(fileName, 'wb') every bit f:
print('file incoming...')
while True:
print('receiving data...')
information = serverSocket.recv(1024)
if not data:
break
f.write(data)
print(fileName + " has been Received!")
serverSocket.close()

# Main office of server, start the file sharing service
def showtime(self):
serverPort=self.port
serverSocket=socket(AF_INET,SOCK_STREAM)
serverSocket.demark(('',serverPort))
serverSocket.listen(20)
print('The server is prepare to receive')
while True:
connectionSocket, addr = serverSocket.accept()
print("**Conn. to ", addr)
dataRec = connectionSocket.recv(1024)
header,msg= protocol.decodeMsg(dataRec.decode()) # get client'due south info, parse it to header and content
# Main logic of the programme, ship different content to client according to customer's requests
if(header== protocol.HEAD_REQUEST):
cocky.listFile(connectionSocket)
elif(header == protocol.HEAD_DOWNLOAD):
self.sendFile(connectionSocket, self.path+"/"+msg)
elif(header == protocol.HEAD_UPLOAD):
cocky.receiveFile(connectionSocket, self.path2+"/"+msg)
else:
connectionSocket.send(protocol.prepareMsg(protocol.HEAD_ERROR, "Invalid Message"))
connectionSocket.close()

def main():
southward=server()
s.start()

main()

Customer.py

                  import config, protocol
from socket import *
import threading
import time
import os
import sys

class client:

fileList= # list to shop the file information
uploadFileList =

#Constructor: load client configuration from config file
def __init__(self):
self.serverName, self.serverPort, self.clientPort, cocky.downloadPath, self.uploadPath = config.config().readClientConfig()

# Function to produce user menu
def printMenu(cocky):
impress("Welcome to simple file sharing organisation!")
print("Delight select operations from carte")
print("--------------------------------------")
print("3. Upload File")
print("5. Quit")

# Office to get user choice from the card
def getUserSelection(self):
ans=0
# only have selection i-iv
while ans>5 or ans<i:
self.printMenu()
endeavour:
ans=int(input())
except:
ans=0
if (ans<=v) and (ans>=i):
return ans
impress("Invalid Selection")

# Build connection to server
def connect(self):
serverName = cocky.serverName
serverPort = self.serverPort
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
return clientSocket

def getUploadFileList(cocky):
self.uploadFileList = os.listdir(self.uploadPath)

def printUploadFileList(self):
count = 0
for f in self.uploadFileList:
count += one
print('{:<3d}{}'.format(count, f))

def selectUploadFile(self):
if (len(self.uploadFileList)==0):
self.getUploadFileList()
ans=-1
while ans<0 or ans>len(self.uploadFileList)+1:
self.printUploadFileList()
impress("Please select the file yous desire to upload from the list (enter the number of files):")
attempt:
ans=int(input())
except:
ans=-1
if (ans>0) and (ans<len(self.uploadFileList)+1):
return self.uploadFileList[ans-one]
impress("Invalid number")

def uploadFile(cocky, fileName):
mySocket=cocky.connect()
mySocket.send(protocol.prepareMsg(protocol.HEAD_UPLOAD, fileName))
f = open(fileName, 'rb')
l = f.read(1024) # each time we only send 1024 bytes of information
while (l):
print('File uploading...')
mySocket.sendall(fifty)
50 = f.read(1024)
f.close()
print("File Uploaded Successfully!")

# Primary logic of the customer, beginning the client application
def start(cocky):
opt=0
while opt!=5:
opt=cocky.getUserSelection()
if opt==3:
cocky.uploadFile(cocky.selectUploadFile())
else:
pass

def main():
c=client()
c.start()

main()

I've defined modules in the protocol file that I accept...

Protocol.py

                  HEAD_LIST='LST'
HEAD_REQUEST='REQ'
HEAD_DOWNLOAD='DLD'
HEAD_UPLOAD='ULD'
HEAD_FILE='FIL'
HEAD_ERROR='ERR'

# we prepare the bulletin that are sent between server and client as the header + content
def prepareMsg(header, msg):
return (header+msg).encode()

def prepareFileList(header,fList):
'''
function to set file list to msg
'''
msg=header
for i in range(len(fList)):
if (i==len(fList)-1):
msg+=fList[i]
else:
msg+=fList[i]+','
return msg.encode()

# Decode the received bulletin, the outset three letters are used as protocol header
def decodeMsg(msg):
if (len(msg)<=iii):
return HEAD_ERROR, 'EMPTY MESSAGE'
else:
return msg[0:three],msg[3:len(msg)]

I've besides divers my config file as follows...

Config.py

                  form config:
#ascertain header
server_port='SERVER_PORT'
path="PATH"
path2="PATH2"
server="SERVER"
client_port="CLIENT_PORT"
download="DOWNLOAD"
upload="UPLOAD"
serverConfig="server.config"
clientConfig="customer.config"

def __init__(self):
pass
def readServerConfig(self):
try:
with open(self.serverConfig,'r') equally f:
serPort=0
sharePath=""
sharePath2=""
for l in f:
sub=l.strip().divide("=")
if(sub[0]==cocky.server_port):
serPort=int(sub[1])
elif(sub[0]==self.path):
sharePath=sub[1]
elif (sub[0] == self.path2):
sharePath2 = sub[one]

else:
pass
return serPort, sharePath, sharePath2
except:
impress(Exception.bulletin())

def readClientConfig(self):
'''
This function read client configuration file, render four values
@return: serverName
@return: serverPort
@render: clientPort
@return: downloadPath
'''
try:
with open(cocky.clientConfig,'r') equally f:
serPort=0
serName=""
clientPort=0
downPath=""
upPath=""
for l in f:
sub=50.strip().split("=")
if(sub[0]==cocky.server_port):
serPort=int(sub[ane])
elif(sub[0]==cocky.server):
serName=sub[1]
elif(sub[0]==self.client_port):
clientPort=sub[1]
elif(sub[0]==self.download):
downPath=sub[ane]
elif(sub[0]==self.upload):
upPath=sub[i]
else:
pass
return serName, serPort, clientPort, downPath, upPath
except:
print(Exception.bulletin())

# The role to test the configuration class
def test():
conf=config()
client=conf.readClientConfig()
server=conf.readServerConfig()
print(customer)
print(server)

The above code will return a file list, I can choose which file I'd like to upload, and the lawmaking volition state its complete just I cannot detect the files on the server. I have test files gear up upward in directories paths on both machines. in addition, my server.config and client.config files are fix upwards as:
server.config

                  SERVER_PORT=12007
PATH=/root/serverFiles
PATH2=/root/files


client.config

                  SERVER=192.168.10.i
SERVER_PORT=12007
CLIENT_PORT=12006
DOWNLOAD=/root/Downloads
UPLOAD=/root/Upload














I'm looking to detect some assistance in my python socket programming.

Objective: upload a file from the Client to the Server. My current setup involves 2 virtual machines, a Server and a Customer, where the respective .py files volition reside; server.py and client.py . The issues I'yard experiencing is, that when I go to cull the upload option, the output reads "File uploading.... File successfully uploaded" Only when I look on the server side, the file doesn't exist - nor practise I receive an error. The server shows that it received a connection when I send the file to upload. What I have currently is below... Any assistance would be greatly appreciated.

Server.py

                import config, protocol
import os
from socket import *
import threading
import time
import sys

class server():

# Constructor: load the server information from config file
def __init__(self):
self.port, self.path, self.path2 = config.config().readServerConfig()

# part to receive file data from client
def receiveFile(self, serverSocket, fileName):
serverSocket.connect()
serverSocket.send(protocol.prepareMsg(protocol.HEAD_UPLOAD, fileName))
with open up(fileName, 'wb') every bit f:
print('file incoming...')
while True:
print('receiving data...')
information = serverSocket.recv(1024)
if not data:
break
f.write(information)
print(fileName + " has been Received!")
serverSocket.shut()

# Chief function of server, start the file sharing service
def start(self):
serverPort=self.port
serverSocket=socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('',serverPort))
serverSocket.listen(20)
impress('The server is ready to receive')
while True:
connectionSocket, addr = serverSocket.accept()
impress("**Conn. to ", addr)
dataRec = connectionSocket.recv(1024)
header,msg= protocol.decodeMsg(dataRec.decode()) # get client's info, parse it to header and content
# Main logic of the programme, ship different content to client co-ordinate to customer's requests
if(header== protocol.HEAD_REQUEST):
cocky.listFile(connectionSocket)
elif(header == protocol.HEAD_DOWNLOAD):
cocky.sendFile(connectionSocket, cocky.path+"/"+msg)
elif(header == protocol.HEAD_UPLOAD):
self.receiveFile(connectionSocket, self.path2+"/"+msg)
else:
connectionSocket.transport(protocol.prepareMsg(protocol.HEAD_ERROR, "Invalid Message"))
connectionSocket.close()

def main():
s=server()
s.start()

main()

Customer.py

                import config, protocol
from socket import *
import threading
import time
import os
import sys

class client:

fileList= # listing to store the file information
uploadFileList =

#Constructor: load customer configuration from config file
def __init__(self):
self.serverName, self.serverPort, self.clientPort, self.downloadPath, self.uploadPath = config.config().readClientConfig()

# Function to produce user menu
def printMenu(self):
print("Welcome to simple file sharing system!")
impress("Please select operations from carte")
print("--------------------------------------")
impress("3. Upload File")
print("5. Quit")

# Role to get user selection from the menu
def getUserSelection(self):
ans=0
# just accept pick one-4
while ans>5 or ans<i:
self.printMenu()
try:
ans=int(input())
except:
ans=0
if (ans<=v) and (ans>=1):
return ans
impress("Invalid Option")

# Build connection to server
def connect(self):
serverName = cocky.serverName
serverPort = self.serverPort
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
return clientSocket

def getUploadFileList(cocky):
cocky.uploadFileList = bone.listdir(self.uploadPath)

def printUploadFileList(cocky):
count = 0
for f in self.uploadFileList:
count += 1
print('{:<3d}{}'.format(count, f))

def selectUploadFile(self):
if (len(self.uploadFileList)==0):
cocky.getUploadFileList()
ans=-ane
while ans<0 or ans>len(self.uploadFileList)+ane:
self.printUploadFileList()
print("Please select the file you lot want to upload from the listing (enter the number of files):")
try:
ans=int(input())
except:
ans=-1
if (ans>0) and (ans<len(self.uploadFileList)+1):
return self.uploadFileList[ans-1]
impress("Invalid number")

def uploadFile(self, fileName):
mySocket=self.connect()
mySocket.send(protocol.prepareMsg(protocol.HEAD_UPLOAD, fileName))
f = open(fileName, 'rb')
l = f.read(1024) # each time nosotros merely send 1024 bytes of data
while (l):
print('File uploading...')
mySocket.sendall(l)
l = f.read(1024)
f.close()
print("File Uploaded Successfully!")

# Main logic of the client, start the client application
def starting time(self):
opt=0
while opt!=five:
opt=self.getUserSelection()
if opt==3:
cocky.uploadFile(self.selectUploadFile())
else:
pass

def main():
c=client()
c.outset()

master()

I've defined modules in the protocol file that I have...

Protocol.py

                HEAD_LIST='LST'
HEAD_REQUEST='REQ'
HEAD_DOWNLOAD='DLD'
HEAD_UPLOAD='ULD'
HEAD_FILE='FIL'
HEAD_ERROR='ERR'

# we prepare the bulletin that are sent betwixt server and customer as the header + content
def prepareMsg(header, msg):
render (header+msg).encode()

def prepareFileList(header,fList):
'''
role to prepare file list to msg
'''
msg=header
for i in range(len(fList)):
if (i==len(fList)-ane):
msg+=fList[i]
else:
msg+=fList[i]+','
return msg.encode()

# Decode the received bulletin, the first three letters are used as protocol header
def decodeMsg(msg):
if (len(msg)<=3):
return HEAD_ERROR, 'EMPTY MESSAGE'
else:
return msg[0:3],msg[three:len(msg)]

I've also defined my config file as follows...

Config.py

                form config:
#define header
server_port='SERVER_PORT'
path="PATH"
path2="PATH2"
server="SERVER"
client_port="CLIENT_PORT"
download="DOWNLOAD"
upload="UPLOAD"
serverConfig="server.config"
clientConfig="client.config"

def __init__(self):
pass
def readServerConfig(self):
try:
with open(self.serverConfig,'r') as f:
serPort=0
sharePath=""
sharePath2=""
for l in f:
sub=fifty.strip().split("=")
if(sub[0]==cocky.server_port):
serPort=int(sub[1])
elif(sub[0]==self.path):
sharePath=sub[1]
elif (sub[0] == self.path2):
sharePath2 = sub[1]

else:
pass
render serPort, sharePath, sharePath2
except:
print(Exception.message())

def readClientConfig(self):
'''
This function read client configuration file, return four values
@return: serverName
@return: serverPort
@return: clientPort
@render: downloadPath
'''
effort:
with open up(self.clientConfig,'r') as f:
serPort=0
serName=""
clientPort=0
downPath=""
upPath=""
for l in f:
sub=l.strip().split("=")
if(sub[0]==self.server_port):
serPort=int(sub[1])
elif(sub[0]==cocky.server):
serName=sub[1]
elif(sub[0]==self.client_port):
clientPort=sub[1]
elif(sub[0]==self.download):
downPath=sub[1]
elif(sub[0]==self.upload):
upPath=sub[1]
else:
pass
render serName, serPort, clientPort, downPath, upPath
except:
impress(Exception.bulletin())

# The function to test the configuration class
def test():
conf=config()
client=conf.readClientConfig()
server=conf.readServerConfig()
impress(client)
print(server)

The above code will return a file list, I can cull which file I'd similar to upload, and the code will state its consummate simply I cannot find the files on the server. I have test files set up in directories paths on both machines. in add-on, my server.config and customer.config files are set up as:
server.config

                SERVER_PORT=12007
PATH=/root/serverFiles
PATH2=/root/files


client.config

                SERVER=192.168.10.1
SERVER_PORT=12007
CLIENT_PORT=12006
DOWNLOAD=/root/Downloads
UPLOAD=/root/Upload














1


ane




I'thousand looking to discover some assist in my python socket programming.

Objective: upload a file from the Client to the Server. My electric current setup involves two virtual machines, a Server and a Customer, where the respective .py files will reside; server.py and client.py . The issues I'g experiencing is, that when I get to choose the upload option, the output reads "File uploading.... File successfully uploaded" But when I look on the server side, the file doesn't exist - nor practice I receive an error. The server shows that it received a connectedness when I send the file to upload. What I have currently is below... Any assistance would be greatly appreciated.

Server.py

              import config, protocol
import os
from socket import *
import threading
import fourth dimension
import sys

class server():

# Constructor: load the server information from config file
def __init__(self):
self.port, cocky.path, self.path2 = config.config().readServerConfig()

# part to receive file information from client
def receiveFile(self, serverSocket, fileName):
serverSocket.connect()
serverSocket.send(protocol.prepareMsg(protocol.HEAD_UPLOAD, fileName))
with open up(fileName, 'wb') as f:
impress('file incoming...')
while True:
impress('receiving data...')
data = serverSocket.recv(1024)
if non data:
break
f.write(data)
impress(fileName + " has been Received!")
serverSocket.close()

# Main part of server, start the file sharing service
def start(self):
serverPort=self.port
serverSocket=socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('',serverPort))
serverSocket.listen(twenty)
print('The server is ready to receive')
while Truthful:
connectionSocket, addr = serverSocket.accept()
print("**Conn. to ", addr)
dataRec = connectionSocket.recv(1024)
header,msg= protocol.decodeMsg(dataRec.decode()) # get client'southward info, parse it to header and content
# Chief logic of the program, ship different content to client according to client's requests
if(header== protocol.HEAD_REQUEST):
self.listFile(connectionSocket)
elif(header == protocol.HEAD_DOWNLOAD):
self.sendFile(connectionSocket, self.path+"/"+msg)
elif(header == protocol.HEAD_UPLOAD):
self.receiveFile(connectionSocket, cocky.path2+"/"+msg)
else:
connectionSocket.ship(protocol.prepareMsg(protocol.HEAD_ERROR, "Invalid Message"))
connectionSocket.close()

def primary():
s=server()
s.start()

chief()

Customer.py

              import config, protocol
from socket import *
import threading
import time
import os
import sys

class client:

fileList= # listing to store the file information
uploadFileList =

#Constructor: load customer configuration from config file
def __init__(cocky):
cocky.serverName, self.serverPort, self.clientPort, self.downloadPath, self.uploadPath = config.config().readClientConfig()

# Part to produce user menu
def printMenu(self):
print("Welcome to simple file sharing system!")
print("Please select operations from menu")
impress("--------------------------------------")
print("3. Upload File")
print("5. Quit")

# Function to get user selection from the menu
def getUserSelection(cocky):
ans=0
# only have choice ane-4
while ans>5 or ans<i:
self.printMenu()
try:
ans=int(input())
except:
ans=0
if (ans<=v) and (ans>=i):
render ans
print("Invalid Pick")

# Build connection to server
def connect(self):
serverName = self.serverName
serverPort = cocky.serverPort
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
return clientSocket

def getUploadFileList(self):
self.uploadFileList = os.listdir(self.uploadPath)

def printUploadFileList(self):
count = 0
for f in self.uploadFileList:
count += 1
print('{:<3d}{}'.format(count, f))

def selectUploadFile(cocky):
if (len(self.uploadFileList)==0):
self.getUploadFileList()
ans=-ane
while ans<0 or ans>len(self.uploadFileList)+i:
self.printUploadFileList()
print("Please select the file y'all want to upload from the list (enter the number of files):")
try:
ans=int(input())
except:
ans=-i
if (ans>0) and (ans<len(self.uploadFileList)+1):
return cocky.uploadFileList[ans-i]
print("Invalid number")

def uploadFile(self, fileName):
mySocket=self.connect()
mySocket.send(protocol.prepareMsg(protocol.HEAD_UPLOAD, fileName))
f = open(fileName, 'rb')
l = f.read(1024) # each time we only send 1024 bytes of data
while (l):
print('File uploading...')
mySocket.sendall(l)
l = f.read(1024)
f.close()
print("File Uploaded Successfully!")

# Main logic of the client, start the client application
def outset(self):
opt=0
while opt!=5:
opt=self.getUserSelection()
if opt==3:
self.uploadFile(self.selectUploadFile())
else:
laissez passer

def main():
c=client()
c.start()

main()

I've divers modules in the protocol file that I have...

Protocol.py

              HEAD_LIST='LST'
HEAD_REQUEST='REQ'
HEAD_DOWNLOAD='DLD'
HEAD_UPLOAD='ULD'
HEAD_FILE='FIL'
HEAD_ERROR='ERR'

# we fix the message that are sent between server and customer equally the header + content
def prepareMsg(header, msg):
render (header+msg).encode()

def prepareFileList(header,fList):
'''
function to prepare file list to msg
'''
msg=header
for i in range(len(fList)):
if (i==len(fList)-ane):
msg+=fList[i]
else:
msg+=fList[i]+','
return msg.encode()

# Decode the received message, the first three messages are used as protocol header
def decodeMsg(msg):
if (len(msg)<=iii):
render HEAD_ERROR, 'EMPTY Message'
else:
return msg[0:3],msg[three:len(msg)]

I've also defined my config file every bit follows...

Config.py

              class config:
#define header
server_port='SERVER_PORT'
path="PATH"
path2="PATH2"
server="SERVER"
client_port="CLIENT_PORT"
download="DOWNLOAD"
upload="UPLOAD"
serverConfig="server.config"
clientConfig="client.config"

def __init__(self):
laissez passer
def readServerConfig(cocky):
attempt:
with open up(cocky.serverConfig,'r') every bit f:
serPort=0
sharePath=""
sharePath2=""
for l in f:
sub=l.strip().split("=")
if(sub[0]==self.server_port):
serPort=int(sub[1])
elif(sub[0]==self.path):
sharePath=sub[1]
elif (sub[0] == self.path2):
sharePath2 = sub[1]

else:
pass
return serPort, sharePath, sharePath2
except:
print(Exception.message())

def readClientConfig(self):
'''
This function read customer configuration file, return four values
@return: serverName
@return: serverPort
@render: clientPort
@return: downloadPath
'''
endeavor:
with open(self.clientConfig,'r') every bit f:
serPort=0
serName=""
clientPort=0
downPath=""
upPath=""
for l in f:
sub=l.strip().carve up("=")
if(sub[0]==self.server_port):
serPort=int(sub[one])
elif(sub[0]==self.server):
serName=sub[1]
elif(sub[0]==self.client_port):
clientPort=sub[1]
elif(sub[0]==self.download):
downPath=sub[1]
elif(sub[0]==cocky.upload):
upPath=sub[1]
else:
pass
return serName, serPort, clientPort, downPath, upPath
except:
print(Exception.message())

# The part to test the configuration class
def exam():
conf=config()
customer=conf.readClientConfig()
server=conf.readServerConfig()
impress(client)
print(server)

The in a higher place code volition return a file list, I tin choose which file I'd like to upload, and the code volition state its complete but I cannot find the files on the server. I have examination files gear up up in directories paths on both machines. in addition, my server.config and client.config files are set up upward as:
server.config

              SERVER_PORT=12007
PATH=/root/serverFiles
PATH2=/root/files


customer.config

              SERVER=192.168.10.ane
SERVER_PORT=12007
CLIENT_PORT=12006
DOWNLOAD=/root/Downloads
UPLOAD=/root/Upload











I'm looking to notice some assistance in my python socket programming.

Objective: upload a file from the Client to the Server. My electric current setup involves two virtual machines, a Server and a Client, where the respective .py files will reside; server.py and client.py . The issues I'm experiencing is, that when I go to cull the upload selection, the output reads "File uploading.... File successfully uploaded" Simply when I wait on the server side, the file doesn't be - nor exercise I receive an mistake. The server shows that information technology received a connectedness when I ship the file to upload. What I have currently is beneath... Any assistance would be profoundly appreciated.

Server.py

            import config, protocol
import os
from socket import *
import threading
import fourth dimension
import sys

form server():

# Constructor: load the server information from config file
def __init__(self):
self.port, cocky.path, self.path2 = config.config().readServerConfig()

# function to receive file data from client
def receiveFile(self, serverSocket, fileName):
serverSocket.connect()
serverSocket.ship(protocol.prepareMsg(protocol.HEAD_UPLOAD, fileName))
with open(fileName, 'wb') every bit f:
print('file incoming...')
while True:
print('receiving data...')
data = serverSocket.recv(1024)
if not information:
break
f.write(data)
impress(fileName + " has been Received!")
serverSocket.close()

# Main function of server, start the file sharing service
def start(self):
serverPort=self.port
serverSocket=socket(AF_INET,SOCK_STREAM)
serverSocket.demark(('',serverPort))
serverSocket.mind(20)
print('The server is ready to receive')
while Truthful:
connectionSocket, addr = serverSocket.accept()
print("**Conn. to ", addr)
dataRec = connectionSocket.recv(1024)
header,msg= protocol.decodeMsg(dataRec.decode()) # get client's info, parse information technology to header and content
# Principal logic of the program, send different content to client co-ordinate to client'due south requests
if(header== protocol.HEAD_REQUEST):
self.listFile(connectionSocket)
elif(header == protocol.HEAD_DOWNLOAD):
self.sendFile(connectionSocket, self.path+"/"+msg)
elif(header == protocol.HEAD_UPLOAD):
cocky.receiveFile(connectionSocket, self.path2+"/"+msg)
else:
connectionSocket.send(protocol.prepareMsg(protocol.HEAD_ERROR, "Invalid Message"))
connectionSocket.close()

def principal():
southward=server()
due south.start()

principal()

Client.py

            import config, protocol
from socket import *
import threading
import fourth dimension
import bone
import sys

form client:

fileList= # list to shop the file information
uploadFileList =

#Constructor: load customer configuration from config file
def __init__(self):
self.serverName, self.serverPort, self.clientPort, self.downloadPath, self.uploadPath = config.config().readClientConfig()

# Office to produce user menu
def printMenu(self):
print("Welcome to unproblematic file sharing system!")
impress("Delight select operations from menu")
impress("--------------------------------------")
impress("3. Upload File")
print("5. Quit")

# Function to get user option from the menu
def getUserSelection(self):
ans=0
# only accept option 1-4
while ans>5 or ans<1:
self.printMenu()
try:
ans=int(input())
except:
ans=0
if (ans<=5) and (ans>=1):
return ans
print("Invalid Option")

# Build connection to server
def connect(cocky):
serverName = self.serverName
serverPort = self.serverPort
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
return clientSocket

def getUploadFileList(self):
self.uploadFileList = bone.listdir(self.uploadPath)

def printUploadFileList(cocky):
count = 0
for f in self.uploadFileList:
count += 1
print('{:<3d}{}'.format(count, f))

def selectUploadFile(cocky):
if (len(self.uploadFileList)==0):
self.getUploadFileList()
ans=-1
while ans<0 or ans>len(cocky.uploadFileList)+1:
self.printUploadFileList()
print("Please select the file you want to upload from the list (enter the number of files):")
try:
ans=int(input())
except:
ans=-1
if (ans>0) and (ans<len(cocky.uploadFileList)+one):
return self.uploadFileList[ans-1]
print("Invalid number")

def uploadFile(cocky, fileName):
mySocket=self.connect()
mySocket.send(protocol.prepareMsg(protocol.HEAD_UPLOAD, fileName))
f = open up(fileName, 'rb')
l = f.read(1024) # each time we but send 1024 bytes of data
while (l):
print('File uploading...')
mySocket.sendall(l)
l = f.read(1024)
f.close()
print("File Uploaded Successfully!")

# Primary logic of the client, start the client application
def start(self):
opt=0
while opt!=5:
opt=self.getUserSelection()
if opt==3:
self.uploadFile(self.selectUploadFile())
else:
pass

def main():
c=client()
c.start()

master()

I've defined modules in the protocol file that I have...

Protocol.py

            HEAD_LIST='LST'
HEAD_REQUEST='REQ'
HEAD_DOWNLOAD='DLD'
HEAD_UPLOAD='ULD'
HEAD_FILE='FIL'
HEAD_ERROR='ERR'

# we set up the message that are sent betwixt server and customer as the header + content
def prepareMsg(header, msg):
return (header+msg).encode()

def prepareFileList(header,fList):
'''
part to prepare file listing to msg
'''
msg=header
for i in range(len(fList)):
if (i==len(fList)-1):
msg+=fList[i]
else:
msg+=fList[i]+','
render msg.encode()

# Decode the received message, the beginning iii letters are used as protocol header
def decodeMsg(msg):
if (len(msg)<=three):
return HEAD_ERROR, 'EMPTY MESSAGE'
else:
return msg[0:3],msg[3:len(msg)]

I've also defined my config file as follows...

Config.py

            class config:
#define header
server_port='SERVER_PORT'
path="PATH"
path2="PATH2"
server="SERVER"
client_port="CLIENT_PORT"
download="DOWNLOAD"
upload="UPLOAD"
serverConfig="server.config"
clientConfig="client.config"

def __init__(self):
pass
def readServerConfig(self):
endeavor:
with open(self.serverConfig,'r') as f:
serPort=0
sharePath=""
sharePath2=""
for l in f:
sub=l.strip().split("=")
if(sub[0]==self.server_port):
serPort=int(sub[1])
elif(sub[0]==self.path):
sharePath=sub[1]
elif (sub[0] == self.path2):
sharePath2 = sub[one]

else:
laissez passer
render serPort, sharePath, sharePath2
except:
print(Exception.message())

def readClientConfig(self):
'''
This function read client configuration file, return four values
@return: serverName
@render: serverPort
@return: clientPort
@render: downloadPath
'''
endeavor:
with open up(self.clientConfig,'r') equally f:
serPort=0
serName=""
clientPort=0
downPath=""
upPath=""
for l in f:
sub=l.strip().dissever("=")
if(sub[0]==self.server_port):
serPort=int(sub[1])
elif(sub[0]==self.server):
serName=sub[1]
elif(sub[0]==self.client_port):
clientPort=sub[ane]
elif(sub[0]==self.download):
downPath=sub[1]
elif(sub[0]==self.upload):
upPath=sub[ane]
else:
pass
return serName, serPort, clientPort, downPath, upPath
except:
print(Exception.message())

# The function to test the configuration class
def exam():
conf=config()
client=conf.readClientConfig()
server=conf.readServerConfig()
impress(client)
print(server)

The to a higher place code will return a file list, I can choose which file I'd like to upload, and the code volition country its complete simply I cannot find the files on the server. I take exam files set upwardly in directories paths on both machines. in addition, my server.config and customer.config files are ready as:
server.config

            SERVER_PORT=12007
PATH=/root/serverFiles
PATH2=/root/files


client.config

            SERVER=192.168.10.1
SERVER_PORT=12007
CLIENT_PORT=12006
DOWNLOAD=/root/Downloads
UPLOAD=/root/Upload





python sockets unix filesystems virtual-machine




























edited November 17 '18 at 20:25














asked Nov 17 '18 at 17:58






















Your uploadFile() method will connect() to the server so sendall() the file content (in 1024 byte chunks).

Your server, on the other hand, will receive the first 1024 bytes (i.e. the first 1024 bytes of file content), and translate it according to the protocol, looking at the showtime three bytes of the file content. The customer, however, never sends protocol.HEAD_UPLOAD as the server expects.

(BTW, I would really recommend y'all PEP8 the code, and refrain from * imports. It makes the code much easier to read, and thus to aid.)








Your Reply

StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", part () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".divide(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to burn down editor subsequently snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", role() {
createEditor();
});
}
else {
createEditor();
}
});

role createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: faux,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered past u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/iii.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:truthful
});

}
});

StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53353987%2fpython-socket-programming-upload-files-from-client-to-server%23new-answer', 'question_page');
}
);

Post as a invitee






Required, but never shown



















Your uploadFile() method will connect() to the server and and so sendall() the file content (in 1024 byte chunks).

Your server, on the other manus, will receive the beginning 1024 bytes (i.e. the outset 1024 bytes of file content), and interpret it according to the protocol, looking at the first three bytes of the file content. The client, however, never sends protocol.HEAD_UPLOAD as the server expects.

(BTW, I would really recommend you PEP8 the code, and refrain from * imports. Information technology makes the code much easier to read, and thus to help.)












Your uploadFile() method will connect() to the server and then sendall() the file content (in 1024 byte chunks).

Your server, on the other hand, volition receive the first 1024 bytes (i.e. the first 1024 bytes of file content), and interpret it according to the protocol, looking at the first three bytes of the file content. The client, however, never sends protocol.HEAD_UPLOAD equally the server expects.

(BTW, I would really recommend y'all PEP8 the code, and refrain from * imports. It makes the lawmaking much easier to read, and thus to help.)












1






Your uploadFile() method will connect() to the server and and then sendall() the file content (in 1024 byte chunks).

Your server, on the other hand, will receive the first 1024 bytes (i.e. the first 1024 bytes of file content), and interpret it co-ordinate to the protocol, looking at the showtime 3 bytes of the file content. The client, still, never sends protocol.HEAD_UPLOAD as the server expects.

(BTW, I would actually recommend you lot PEP8 the code, and refrain from * imports. It makes the code much easier to read, and thus to aid.)









Your uploadFile() method will connect() to the server and and so sendall() the file content (in 1024 byte chunks).

Your server, on the other hand, will receive the first 1024 bytes (i.e. the beginning 1024 bytes of file content), and interpret it according to the protocol, looking at the commencement three bytes of the file content. The client, however, never sends protocol.HEAD_UPLOAD as the server expects.

(BTW, I would really recommend you PEP8 the code, and refrain from * imports. It makes the lawmaking much easier to read, and thus to assistance.)


















answered Nov 17 'eighteen at 19:03































































Cheers for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

Only avoid



  • Request for assistance, clarification, or responding to other answers.

  • Making statements based on stance; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




Some of your past answers have non been well-received, and you're in danger of being blocked from answering.

Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Request for help, clarification, or responding to other answers.

  • Making statements based on stance; back them up with references or personal experience.

To learn more, see our tips on writing neat answers.














StackExchange.fix(
role () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53353987%2fpython-socket-programming-upload-files-from-client-to-server%23new-reply', 'question_page');
}
);

Postal service every bit a guest






Required, but never shown































Required, simply never shown










Required, but never shown








Required, but never shown





Required, merely never shown















Required, but never shown










Required, but never shown








Required, but never shown





Required, but never shown





harttrook1973.blogspot.com

Source: https://cfrgtkky.blogspot.com/2019/01/python-socket-programming-upload-files.html

0 Response to "What Happened on Tcp When Uploading a File"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel