i am trying to make a server and client which sends a file from client to server and the server saves it to hard then the server asks for another file and if the answer of client is yes then the client sends the second file then the server again saves it and if the client answer is no server close the socket when i run this code the first file is sent
and received successfully but after that both of the server and the client freeze and nothing happens what is wrong with it and how can i fix it?
my server code:
import socket
host = 'localhost'
port = 4444
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(5)
(client, (ip, port))=s.accept()
while True:
data = "".join(iter(lambda: client.recv(1), "\n"))
with open('filehere.txt', 'w') as file:
for item in data:
file.write("%s" % item)
if not data: break
client.send("is there any other file?")
d = client.recv(2048)
if d == "yes":
while True:
data = "".join(iter(lambda: client.recv(1), "\n")
with open('filehere1.txt', 'w') as file:
for item in data:
file.write("%s" % item)
if not data: break
s.close()
else:
s.close()
my client code:
import socket
host = 'locahost'
port = 4444
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
f = open('myfile.txt', 'rb')
l = f.read()
while True:
for line in l:
s.send(line)
break
f.close()
d = s.recv(2048)
a = raw_input(d)
if a == "yes":
s.send("yes")
f = open('myfile1', 'rb')
l = f.read()
while True:
for line in l:
s.send(line)
break
f.close()
else:
s.close
Why did you check a == "yes" on client side even when server is not sending "yes"
I think you can check a == "is there any other file?" insted
Related
Im doing socket programming and within the code i open the list of files using TCP socket programming but i have to download a particular file from the server to the client using UDP socket programming but when i download the file it doesn't contain any of whats in the file. please help. the file used is file1.txt which could contain anything but i need for the code to be corrected to provide the information inside the file to display in the client side of the download. ive been trying foe days to fix it but nothing has been working. this is the code
server.py
from socket import *
import os
import sys
import time
SIZE = 1024
serverPort = 1749
serverUDPPort = 9968
fileName = sys.argv[0]
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocketUDP = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind(('', serverPort))
serverSocket.listen(1)
print('The server is running')
while True:
connectionSocket, addr = serverSocket.accept() #accept connection from client
clientMessage = connectionSocket.recv(1024).decode() #client receives file
#print(clientMessage)
s = ""
if clientMessage == "listallfiles":
files = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in files:
s += f + " "
connectionSocket.send(s.encode())
#connectionSocket.send("EOF".encode())
elif clientMessage.startswith("download "):
clientMessage = connectionSocket.recvfrom(1024).decode() #client receives file
if clientMessage == "download all": #if the clients whats to download all the files
print("")
else: #if the client wants to download just one file use UDP
end = len(clientMessage)
fileName == clientMessage[9:end]
serverSocketUDP.sendto(fileName,("", serverUDPPort))
print ("sending...")
fls = open(fileName, "r")
data = fls.read(1024)
#serverSocketUDP.sendto(fileName,addr)
#serverSocketUDP.sendto(data,addr)
while(data):
if(serverSocketUDP.sendto(data, ("", serverUDPPort))):
data = fls.read(1024)
time.sleep(0.02)
serverSocketUDP.close()
fls.close()
break
#if client wants to exit socket
elif clientMessage == "exit":
clientMessage = connectionSocket.recv(1024).decode() #client receives file
print(clientMessage)
connectionSocket.close()
client.py
from select import select
from socket import *
import sys
import time
serverName = '127.0.0.1'
serverPort = 1749
serverUDPPort = 9968
fileName = sys.argv[0]
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocketUDP = socket(AF_INET, SOCK_DGRAM)
clientSocketUDP.bind((serverName,serverUDPPort))
clientSocket.connect((serverName, serverPort)) #connecting to server TCP
clientSocketUDP.connect((serverName, serverPort)) #connecting to server UDP
while True:
sentence = input("")
clientSocket.send(sentence.encode()) #sends message to server
s = ""
#while (True):
if sentence == "listallfiles":
modifiedSentence = clientSocket.recv(1024) #it is receiving message form server
#if modifiedSentence == "EOF".encode():
# break
s += modifiedSentence.decode()
print(s)
elif sentence.startswith("download "):
#clientSocketUDP.sendto(sentence.encode(), (serverName, serverUDPPort)) #sends message to server
#downloading all files
if sentence == "download all":
while (1):
print("")
#download one file
else:
end = len(sentence)
fileName == sentence[9:end]
while True:
data,addr = clientSocketUDP.recvfrom(1024) #download one using UDP
if data:
print ("file name: ", data)
fls = open(sentence, 'wb')
while True:
ready = select.select([clientSocketUDP], [], [], timeout)
if ready[0]:
data, addr = clientSocketUDP.recvfrom(1024)
fls.write(data)
else:
fls.close()
break
#try:
# while (data):
# fls.write(data)
# clientSocketUDP.settimeout(2)
# data,addr = clientSocketUDP.recvfrom(1024) #download one using UDP
#except timeout:
# fls.close()
# clientSocketUDP.close()
# #time.sleep(0.02)
#if client wants to exit socket
elif sentence == "exit":
clientSocket.send(sentence.encode()) #send exit message to server
clientSocket.close()
I am learning the socket programming client server architecture in python. I made this program to send multiple files one by one from client to server. The client program queries the user to type the name of the file and then sends this name to server, where server opens a new file with that name in append+binary mode. But apparently the server creates a new file only the first time but not the other times. it simply appends the next files in the existing file. Please take a look.
#server.py
from socket import *
HOST = ''
PORT = 32000
ADDRESS = (HOST, PORT)
BUFF_SIZE = 1024
tcpServerSocket = socket(AF_INET, SOCK_STREAM)
tcpServerSocket.bind(ADDRESS)
tcpServerSocket.listen(5)
print("waiting for connection..")
client, addr = tcpServerSocket.accept()
print("connected with {}".format(addr))
name = client.recv(BUFF_SIZE).decode()
while True:
if not name:
break
f = open(name, 'ab')
data = client.recv(BUFF_SIZE)
while data:
f.write(data)
data = client.recv(BUFF_SIZE)
f.close()
name = client.recv(BUFF_SIZE)
name = name.decode()
tcpServerSocket.close()
and this is client.py
from socket import *
HOST = "localhost"
PORT = 32000
ADDRESS = (HOST, PORT)
BUFF_SIZE = 1024
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect(ADDRESS)
while True:
name = input("please enter file name: \n")
clientSocket.send(name.encode())
if not name:
break
f = open(name, 'rb')
data = f.read(BUFF_SIZE)
while data:
clientSocket.send(data)
data = f.read(BUFF_SIZE)
f.close()
choice = input("Do you wanna send another file: y/n ?")
if choice.lower() != 'y':
clientSocket.send("".encode())
break
clientSocket.close()
I want to know is there a flush method like function which closes the existing file/stream completely and creates a new one every time.
I thing here is the problem. I didnt try it though. name the new file INSIDE the While true loop
#server.py
from socket import *
HOST = ''
PORT = 32000
ADDRESS = (HOST, PORT)
BUFF_SIZE = 1024
tcpServerSocket = socket(AF_INET, SOCK_STREAM)
tcpServerSocket.bind(ADDRESS)
tcpServerSocket.listen(5)
print("waiting for connection..")
client, addr = tcpServerSocket.accept()
print("connected with {}".format(addr))
while True:
name = client.recv(BUFF_SIZE).decode()
if not name:
break
f = open(name, 'ab')
data = client.recv(BUFF_SIZE)
while data:
f.write(data)
data = client.recv(BUFF_SIZE)
f.close()
name = client.recv(BUFF_SIZE)
name = name.decode()
tcpServerSocket.close()
I am trying to make simple client server program to send and receive file form server using tcp sockets. As far as getting files from server is not an issue, server creates a file with the same name and put data in that file but when it comes to putting files to server,sometimes it works great but always chance so mostly server is getting file name along with file contents and instead of writing that to file, it writes both filename and contents as new file name and that file remains empty. Will be great help if someone can suggest any solution.
server.py
import socket
import sys
HOST = 'localhost'
PORT = 3820
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind((HOST, PORT))
socket.listen(1)
while (1):
conn, addr = socket.accept()
print 'New client connected ..'
reqCommand = conn.recv(1024)
print 'Client> %s' %(reqCommand)
if (reqCommand == 'quit'):
break
#elif (reqCommand == lls):
#list file in server directory
else:
string = reqCommand.split(' ', 1) #in case of 'put' and 'get' method
reqFile = string[1]
if (string[0] == 'put'):
with open(reqFile, 'wb') as file_to_write:
data=conn.recv(1024)
while True:
if not data:
break
else:
file_to_write.write(data)
data=conn.recv(1024)
file_to_write.close()
break
print 'Receive Successful'
elif (string[0] == 'get'):
with open(reqFile, 'rb') as file_to_send:
for data in file_to_send:
conn.sendall(data)
print 'Send Successful'
conn.close()
socket.close()
client.py
import socket
import sys
HOST = 'localhost' # server name goes in here
PORT = 3820
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('clientfolder/'+inputFile, 'rb') as file_to_send:
data=file_to_send.read(1024)
while(data):
socket1.send(data)
data=file_to_send.read(1024)
file_to_send.close()
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('clientfolder/'+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
msg = raw_input('Enter your name: ')
while(1):
print 'Instruction'
print '"put [filename]" to send the file the server '
print '"get [filename]" to download the file from the server '
print '"ls" to list all files in this directory'
print '"lls" to list all files in the server'
print '"quit" to exit'
sys.stdout.write('%s> ' % msg)
inputCommand = sys.stdin.readline().strip()
if (inputCommand == 'quit'):
socket.send('quit')
break
# elif (inputCommand == 'ls')
# elif (inputCommand == 'lls')
else:
string = inputCommand.split(' ', 1)
if (string[0] == 'put'):
put(inputCommand)
elif (string[0] == 'get'):
get(inputCommand)
#current working directory is server location
#get will get file from current directory to clientfolder directory.
TCP is a streaming protocol, so you have to design message breaks into your protocol. For example:
s.send('put filename')
s.send('data')
Can be received as:
s.recv(1024)
# 'put filenamedata'
So buffer data received and only extract full messages. One way is to send the size of a message before the message.
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.
When doing the put command I am getting this error. I can't seem to figure out why.
line 41, in
data = client.recv(1024)
error: [Errno 10053] An established connection was aborted by the software in your host machine
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(command):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send(command)
string = command.split(' ', 1)
input_file = string[1]
with open(input_file, 'rb') as file_to_put:
for data in file_to_put:
s.sendall(data)
s.close()
return
def get(command):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send(command)
string = command.split(' ', 1)
input_file = string[1]
with open(input_file, 'wb') as file_to_get:
while True:
data = s.recv(1024)
print data
if not data:
break
file_to_get.write(data)
file_to_get.close()
s.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.close()
print "Closing connection."
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:\\') # listing contents of c: drive
client.send(str(data))
print data
else:
string = data.split(' ', 1)
data_file = string[1]
if (string[0] == 'put'):
with open(data_file, 'wb') as file_to_write: # opening sent filename to write bytes
while True:
data = client.recv(1024)
if not data:
break
file_to_write.write(data) # writing data
file_to_write.close() # closing file
break
print 'Receive Successful'
elif (string[0] == 'get'):
with open('C:\\' + data_file, 'rb') as file_to_send:
for data in file_to_send:
client.send(data)
print 'Send Successful'
client.close()
s.close()
print "Server exiting."