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()
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 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
I have been able to receive the file from the socket and download it, but when I try to push a message from the server to the client the message is never displayed on the client side.
Below is the code and any help would be highly appreciated as I am a novice to network programming.
# get the hostname
host = socket.gethostname()
port = 5000 # initiate port no above 1024
Buffer = 1024
server_socket = socket.socket() # get instance
# look closely. The bind() function takes tuple as argument
server_socket.bind((host, port)) # bind host address and port together
# configure how many client the server can listen simultaneously
server_socket.listen(2)
conn, address = server_socket.accept() # accept new connection
print("Connection from: " + str(address))
f = open("FileFromServer.txt", "wb")
# receive data stream. it won't accept data packet greater than 1024 bytes
data = conn.recv(Buffer)
while data:
f.write(data)
print("from connected user: " + str(data))
data = conn.recv(Buffer)
f.close()
print 'Data Recivede'
datas = 'Recived the file Thanks'
if datas is not '':
conn.send(datas) # send data to the client
conn.close() # close the connection
host = socket.gethostname() # as both code is running on same pc
port = 5000 # socket server port number
client_socket = socket.socket() # instantiate
client_socket.connect((host, port)) # connect to the server
with open('T.txt', 'rb') as f:
print 'file openedfor sending'
l = f.read(1024)
while True:
client_socket.send(l)
l = f.read(1024)
f.close()
print('Done sending')
print('receiving data...')
data = client_socket.recv(1024)
print data
client_socket.close() # close the connection
print 'conection closed
The thing is that you both you server and client socket stuck in the while loop:
try this client.py:
import socket
host = socket.gethostname() # as both code is running on same pc
port = 5000 # socket server port number
client_socket = socket.socket() # instantiate
client_socket.connect((host, port)) # connect to the server
end = '$END MARKER$'
with open('T.txt', 'rb') as f:
print('file opened for sending')
while True:
l = f.read(1024)
if len(l + end) < 1024:
client_socket.send(l+end)
break
client_socket.send(l)
print('Done sending')
print('receiving data...')
data = client_socket.recv(1024)
print(data)
client_socket.close() # close the connection
print('conection closed')
server.py
import socket
# get the hostname
host = socket.gethostname()
port = 5000 # initiate port no above 1024
Buffer = 1024
end = '$END MARKER$'
server_socket = socket.socket() # get instance
# look closely. The bind() function takes tuple as argument
server_socket.bind((host, port)) # bind host address and port together
# configure how many client the server can listen simultaneously
server_socket.listen(2)
conn, address = server_socket.accept() # accept new connection
print("Connection from: " + str(address))
# receive data stream. it won't accept data packet greater than 1024 bytes
with open("FileFromServer.txt", "ab") as f:
while True:
data = conn.recv(Buffer)
if end in data:
f.write(data[:data.find(end)])
conn.send(b'Recived the file Thanks')
break
f.write(data)
conn.close()
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.
I have the following text file:
ADDRESS1 192.168.124.1
ADDRESS2 192.168.124.2
ADDRESS3 192.168.124.3
And I wrote the following string server in python (strsrv.py) :
#!/usr/bin/env python
import socket
import sys
host = ''
port = 50000
backlog = 5
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host,port))
s.listen(backlog)
while 1:
global f
client, address = s.accept()
data = client.recv(size)
with open('list.txt', 'r') as my_file:
for f in my_file.readlines():
if(f.find('%s' % data)>-1):
data = f
if f:
client.send(data)
client.send(f)
client.close()
I'm trying to connect to this server sending a string. This string must match one of lines described on text file. Ex: sending 'ADDRESS1' should return 'ADDRESS1 192.168.124.1' from the server, but it doesn't works. Any string sent returns only the last line of the text file. Please could someone point me to the right direction? Thanks :)
How are you testing this? Assuming you open a socket and connect to the host you should see that you are in fact receiving the correct line as well as the last one. Why? Because in the for loop you keep changing the value of f, the last value of f will be the last line in the file, and you send it back after sending data (which at that point is the correct value).
Here's a suggestion for how you might modify your code (assuming you want the full line back and you dont want wildcarding):
#!/usr/bin/env python
import socket
import sys
host = ''
port = 50000
backlog = 5
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host,port))
s.listen(backlog)
# build dict of addresses first, no need to do this for each message
with open('list.txt', 'r') as my_file:
address_map = dict(line.split() for line in my_file)
while True:
client, address = s.accept()
req_address = client.recv(size)
ip = address_map.get(req_address, 'Not found')
client.send(req_address + ' ' + ip)
client.close()
You can simply test this by doing this while the above is running:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('', 50000))
s.send('ADDRESS2')
s.recv(1024)