Python Client Server program gets stucked - python

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 ??

Related

socket programming using TCP and UDP file transfer

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

python socket listener not receiving data

I am programming a decentralised script to track the IPs of other computers running the script, to explore decentralisation. This script isolates the problem. The code consists of 2 scripts, one main program which sends its IP to an IP provided if one is provided, and a listener program which is run as a subscript and listens for data and pipes that data back to the main program. The main script appears to be working, the data is sent over the network, but the listener does not receive it.
This is the main script
import socket
from subprocess import Popen, PIPE
from time import sleep
def getIP():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(('8.8.8.4', 1))
IP = s.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
s.close()
return IP
def sendfyi(target, ownIP):
toSend = 'fyi' + ':' + ownIP
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((target, 50000))
s.send(toSend.encode())
s.close()
print('sent fyi')
otherIPs = []
ownIP = getIP()
targetIP = input('enter ip or 0: ')
if targetIP != '0':
otherIPs.append(targetIP)
sendfyi(targetIP, ownIP)
listener = Popen(['python3', 'testlistener.py'], stdout=PIPE, stderr=PIPE)
i = 0
while i == 0:
sleep(1)
listenerPipe = listener.stdout.readline()
print(listenerPipe)
This is the sub process:
import socket
def getIP():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
s.connect(('8.8.8.4', 1))
IP = s.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
s.close()
return IP
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((getIP(), 50000))
i = 1
while i == 1:
s.listen(1)
conn, addr = s.accept()
print('conected', flush=True)
data = conn.recv(1024)
print('data receved', flush=True)
out = data.decode()
print('data decoded', flush=True)
print(out, flush=True)
conn.close()
Incorect bind statement
bind(('', 50000))

How to make the server side socket code run continuously

I have a server/client socket program that is used to transfer a file from the client to the server. The issue is that the code stops running once the file is transferred. I want to change it such that the server side code is continuously running so that I can transfer a file multiple times without having to run the code again and again
Server code:
import socket
host = ''
port = 5560
def setupServer():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Socket created.")
try:
s.bind((host, port))
except socket.error as msg:
print(msg)
print("Socket bind comlete.")
return s
def setupConnection():
s.listen(1) # Allows one connection at a time.
conn, address = s.accept()
print("Connected to: " + address[0] + ":" + str(address[1]))
return conn
def storeFile(filePath):
picFile = open(filePath, 'wb')
print(filePath)
print("Opened the file.")
pic = conn.recv(1024)
#print(pic)
while pic:
print("Receiving picture still.")
picFile.write(pic)
pic = conn.recv(1024)
picFile.close()
def dataTransfer(conn):
# A big loop that sends/receives data until told not to.
while True:
# Receive the data
data = conn.recv(1024) # receive the data
data = data.decode('utf-8')
# Split the data such that you separate the command
# from the rest of the data.
dataMessage = data.split(' ', 1)
command = dataMessage[0]
if command == 'GET':
reply = GET()
elif command == 'REPEAT':
reply = REPEAT(dataMessage)
elif command == 'STORE':
print("Store command received. Time to save a picture")
storeFile(dataMessage[1])
reply = "File stored."
elif command == 'LED_ON':
callLED()
reply = 'LED was on'
else:
reply = 'Unknown Command'
# Send the reply back to the client
conn.sendall(str.encode(reply))
#print("Data has been sent!")
conn.close()
s = setupServer()
while True:
try:
conn = setupConnection()
dataTransfer(conn)
except:
break
The client side code is below:
import socket
from time import sleep
from time import time
host = '192.168.0.17'
port = 5560
data = "hi"
filepath = "/var/www/html/unknown.txt"
def setupSocket():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
return s
def sendPic(s, filePath):
print(filePath)
pic = open(filePath, 'rb')
chunk = pic.read(1024)
s.send(str.encode("STORE " + filePath))
t = time()
while chunk:
print("Sending Picture")
s.send(chunk)
#print(chunk)
chunk = pic.read(1024)
pic.close()
print("Done sending")
print("Elapsed time = " + str(time() - t) + 's')
#s.close()
return "Done sending"
def sendReceive(s, message):
s.send(str.encode(message))
reply = s.recv(1024)
print("We have received a reply")
print("Send closing message.")
s.send(str.encode("EXIT"))
#s.close()
reply = reply.decode('utf-8')
return reply
def transmit(message):
s = setupSocket()
response = sendReceive(s, message)
return response
def backup(filePath):
s = setupSocket()
response = sendPic(s, filePath)
return response
while True:
backup(filepath)
print("Backup Complete!")
break
I do not own the code. I have made some change to the code that I got from a YouTube video.
Have you had a look at the SocketServer module?
You could setup your dataTransfer() function as the handle() method of a RequestHandler class, then start your server with the serve_forever() method.

audio over python tcp error

I am writing a simple python tcp code to send over a wav file however I seem to be getting stuck. can someone explain why my code is not working correctly?
Server Code
import socket, time
import scipy.io.wavfile
import numpy as np
def Main():
host = ''
port = 3333
MAX = 65535
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(1)
print "Listening on port..." + str(port)
c, addr = s.accept()
print "Connection from: " + str(addr)
wavFile = np.array([],dtype='int16')
i = 0
while True:
data = c.recvfrom(MAX)
if not data:
break
# print ++i
# wavfile = np.append(wavfile,data)
print data
timestr = time.strftime("%y%m%d-%h%m%s")
print timestr
# wavF = open(timestr + ".wav", "rw+")
scipy.io.wavfile.write(timestr + ".wav",44100, data)
c.close()
if __name__ == '__main__':
Main()
Client Code
host, port = "", 3333
import sys , socket
import scipy.io.wavfile
# create a tcp/ip socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# connect the socket to the port where the server is listening
server_address = (host, port)
print >>sys.stderr, 'connecting to %s port %s' % server_address
input_data = scipy.io.wavfile.read('Voice 005.wav',)
audio = input_data[1]
sock.connect(server_address)
print 'have connected'
try:
# send data
sock.sendall(audio)
print "sent" + str(audio)
sock.close()
except:
print('something failed sending data')
finally:
print >>sys.stderr, 'closing socket'
print "done sending"
sock.close()
Please help someone, I want to send an audio file to my embedded device with tcp since it crucial data to be processed on the embedded device.
Not sure why you go to the trouble of using scipy and numpy for this, since you can just use the array module to create binary arrays that will hold the wave file. Can you adapt and use the simple client/server example below?
(Note: I've copy/pasted a small Windows sound file called 'tada.wav' to the same folder to use with the test scripts.)
Code for the server script:
import socket
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
print('Listening...')
conn, addr = s.accept()
print('Connected by', addr)
outfile = open("newfile.wav", 'ab')
while True:
data = conn.recv(1024)
if not data: break
outfile.write(data)
conn.close()
outfile.close()
print ("Completed.")
Code for the client:
from array import array
from os import stat
import socket
arr = array('B') # create binary array to hold the wave file
result = stat("tada.wav") # sample file is in the same folder
f = open("tada.wav", 'rb')
arr.fromfile(f, result.st_size) # using file size as the array length
print("Length of data: " + str(len(arr)))
HOST = 'localhost'
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send(arr)
print('Finished sending...')
s.close()
print('done.')
This works for me (though only tested by running both on localhost) and I end up with a second wave file that's an exact copy of the one sent by the client through the socket.

Sending more than one string in socket programming python

I want to send data more than once. I have the following code on server and client:
On server :
import socket
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(14,GPIO.OUT)
GPIO.setup(15,GPIO.OUT)
serversocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host="10.168.1.50"
port=80
print(host)
print(port)
serversocket.bind((host,port))
serversocket.listen(5)
print('server started listening')
while 1:
(clientsocket,address)=serversocket.accept()
print("connection established from : ",address)
data=clientsocket.recv(1024).decode()
print(data)
if (data=='hai'):
GPIO.output(14,True)
GPIO.output(15,False)
print 'hello'
else:
GPIO.output(14,False)
GPIO.output(15,False)
clientsocket.send("data is sent".encode())
On client:
import socket
s = socket.socket()
host = "10.168.1.50"
port = 80
s.connect((host,port))
while True:
in_data=raw_input(" Enter data to be sent > ")
s.send(in_data.encode())
s.send('hai'.encode())
data = ''
data = s.recv(1024).decode()
print (data)
s.close
I send the first string, get the response, but when I send the second string, it hangs.
How can I solve this?
Here is the code that worked
On server :
import socket
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(14,GPIO.OUT)
GPIO.setup(15,GPIO.OUT)
serversocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host="10.168.1.50"
port=80
print(host)
print(port)
serversocket.bind((host,port))
serversocket.listen(5)
print('server started listening')
(clientsocket,address)=serversocket.accept()
print("connection established from : ",address)
while 1:
data=clientsocket.recv(1024).decode()
print(data)
if (data=='hai'):
GPIO.output(14,True)
GPIO.output(15,False)
print 'hello'
else:
GPIO.output(14,False)
GPIO.output(15,False)
clientsocket.send("data is sent".encode())
On client:
import socket
s = socket.socket()
host = "10.168.1.50"
port = 80
s.connect((host,port))
try:
while True:
in_data=raw_input(" Enter data to be sent > ")
s.send(in_data.encode())
data = ''
data = s.recv(1024).decode()
print (data)
finally:
s.close()
This my client and it's working.
import socket
s = socket.socket()
host = "10.168.1.50"
port = 80
s.connect((host,port))
try:
while True:
in_data=raw_input(" Enter data to be sent > ")
s.send(in_data.encode())
s.send('hai'.encode())
data = ''
data = s.recv(1024).decode()
print (data)
finally:
s.close()

Categories