socket programming using TCP and UDP file transfer - python

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()

Related

Is there a way to send data to one client using multi threading socket python

I have a server using socket and multi threading in python I am trying to send data to one client, I can send to both clients using connection.sendall but that sends to both.
Is there a way to send to one client using something like IP address or socket id?
Here is my server.
import socket
from _thread import start_new_thread, get_ident
import pickle
import random
host = '127.0.0.1' #host for socket
port = 46846 #port
ThreadCount = 0
connections = 0
clients = []
name = []
turn = 1
word = random.choice(open('words.txt').read().splitlines()).lower().encode() #grab a word from my file of words
def game(connection): #the games code
print(get_ident()) #id of the socket
name.append(connection.recv(2048).decode('utf-8')) #wait for name
print(name)
while 1: # wait for 2 names
if len(name) == 2:
break
pickled_name = pickle.dumps(name) #encode names
connection.sendall(pickled_name) #send encoded names
connection.sendall(word) #send the word
connection.close() #end off the connection, I want more before this but this is the end for now
def accept_connections(ServerSocket): #start a connection
global connections
Client, address = ServerSocket.accept()
print(f'Connected to: {address[0]}:{str(address[1])}')
start_new_thread(game, (Client, ))
clients.append(Client)
connections = connections + 1
print(connections)
print(clients)
def start_server(host, port): #start the server
ServerSocket = socket.socket()
try:
ServerSocket.bind((host, port))
except socket.error as e:
print(str(e))
print(f'Server is listing on the port {port}...')
ServerSocket.listen()
while True:
accept_connections(ServerSocket)
start_server(host, port)
And here is my client
import socket
import pickle
host = '127.0.0.1'
port = 46846
ClientSocket = socket.socket() #start socketing
print('Waiting for connection')
try:
ClientSocket.connect((host, port)) #connect
except socket.error as e:
print(str(e))
player = input('Your Name: ') #grab name
ClientSocket.send(str.encode(player)) #send name and encode it
data = ClientSocket.recv(1024)
name = ""
while name == "":
name = pickle.loads(data) #grab names from server
mistakeMade=0
print(f"Welcome to the game, {name[0]}, {name[1]}")
word = ClientSocket.recv(1024).decode('utf-8')
print("I am thinking of a word that is",len(word),"letters long.")
print("-------------")
turn = ClientSocket.recv(1024)
print(turn)

how to fix sending string with python socket after sending a file

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

error sending multiple files using client sockets architecture in python

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()

Tcp sockets to send and receive files, using python

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.

Python Client Server program gets stucked

Server Code
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("192.168.169.10", 9559))
server_socket.listen(5)
import os
import time
client_socket, address = server_socket.accept()
print "Conencted to - ",address,"\n"
while(1):
fp = open('img.jpg','wb+')
start = time.time()
while True:
strng = client_socket.recv(1024)
if not strng:
break
print 'loop ends'
fp.write(strng)
fp.close()
print 'total time taken',time.time()-start,'secs'
print "Data Received successfully"
client_socket.send("Hey I am looking for you face")
exit()
Client Code
import socket,os
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("192.168.169.10", 9559))
fname = '/home/student/images/andrew1.jpeg'
img = open(fname,'rb')
while True:
strng = img.readline(1024)
if not strng:
break
client_socket.send(strng)
img.close()
response = client_socket.recv(1024)
print response
exit()
The Code gets stucked and when on the client side ctrl +C is pressed the server exits and the client doesnt receive data
How to achieve two way communication in this scenario ??

Categories