I am trying to use the return from my scan_db() return to pass it through to the next function json_create(response) and use the return from my json_create(response) to pass to my broadcast_string(Sensor_IP, jsonString).
Every time I try to run the program I get the error "NameError: name 'response' is not defined" I cannot find useful examples anywhere.
I am using python 2.7
mycursor = conn.cursor()
def scan_db():
print "Scanning DB"
mycursor.execute("SELECT * FROM outputs ORDER BY ID DESC LIMIT 1;")
response = mycursor.fetchall()
return response
def json_create(response):
ID, Sensor_ID, Sensor_IP, State, Pending_Update, TimeStamp = response[0]
print "Json string creating"
print ""
print "ID", ID
print "Sensor Name", Sensor_ID
print "Sensor IP", Sensor_IP
print "State", State
print "Pending update", Pending_Update
print "Time", TimeStamp
print ""
jsonSwitch = {'Sensor_Name': Sensor_ID, 'Sensor_IP': Sensor_IP, 'State': State,
'Pending_Update': Pending_Update}
jsonString = json.dumps(jsonSwitch)
return jsonString, Sensor_IP
def broadcast_string(Sensor_IP, jsonString):
UDP_IP = Sensor_IP # broadcast
UDP_PORT = 5002
print "UDP target IP:", UDP_IP
print "UDP target port:", UDP_PORT
print "message:", jsonString
cs = socket(AF_INET, SOCK_DGRAM)
cs.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
cs.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
cs.sendto(jsonString, (UDP_IP, UDP_PORT))
while True:
print "while loop started"
scan_db()
print "scanning db"
json_create(response)
print "creating Json string"
broadcast_string(Sensor_IP, jsonString)
print "broadcasting packet"
time.sleep(2)
You haven't stored the result which scan_db() returns so in json_create(response) the response is nothing. Try creating a variable response and setting its contents equal to the value scan_db() returns like so:
while True:
print "while loop started"
response = scan_db() # edit this line
print "scanning db"
json_create(response)
print "creating Json string"
broadcast_string(Sensor_IP, jsonString)
print "broadcasting packet"
time.sleep(2)
similarly you could also do json_create(scan_db())
You should replace this piece of code:
while True:
print "while loop started"
scan_db()
print "scanning db"
json_create(response)
# the rest of your code
# ...
by
while True:
print "while loop started"
# create a new response variable
response = scan_db()
print "scanning db"
json_create(response)
# the rest of your code
# ....
Explication:
Your scan_db() method will return the response variable that you'll use in your json_create(response).
In the while loop, You should
while True:
print "while loop started"
response = scan_db()
print "scanning db"
jsonString, Sensor_IP = json_create(response)
print "creating Json string"
broadcast_string(Sensor_IP, jsonString)
print "broadcasting packet"
time.sleep(2)
Maybe you should learn what is local variable?
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I created a socket server to read the commands from a socket client. In client side, I send ABC and then DEF, in server side, each time I received ABC or DEF from client, the server will send back to client OK.
Server
import socket
import sys
host = socket.gethostname()
port = 12345
server_tcp = socket.socket()
server_tcp.bind((host, port))
server_tcp.listen(5)
while True:
c, addr = server_tcp.accept()
data = c.recv(1024)
print ('data received: %s') % data
if 'ABC' == data:
print ('sending back ok to the client')
texte = 'OK';
n=c.send(texte)
else:
print ('I did not get the right command ABC')
break
data = c.recv(1024)
print ('data received: %s') % data
if 'DEF' == data:
print ('sending back ok to the client')
texte = 'OK';
n=c.send(texte)
else:
print ('I did not get the right command DEF')
break
c.close()
Socket client:
import socket
import sys
host = socket.gethostname()
port = 12345
client_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
rc = client_tcp.connect((host, port))
except:
print('Server not found')
texte = 'ABC';
n=client_tcp.send(texte)
data=client_tcp.recv(1024);
print (data)
if 'OK' == data:
print('good')
else:
print('bad')
texte = 'DEF';
n=client_tcp.send(texte)
data=client_tcp.recv(1024);
print (data)
if 'OK' == data:
print('good')
else:
print('bad')
client_tcp.close() # Close the socket when done
When I set the command in client with order ABC - DEF I receive OK - OK in server. But with DEF - ABC, I just only received only one OK.
Best regards
I made some changes to your code to test it. The problem is that you are not sending the response that the client is waiting for. It happens when the wrong command arrives.
if your client is waiting for information YOUR SERVER MUST SENDS INFORMATION!... and it's the same for the other side (Server).
In the end, your problem is an issue of protocol. You must design what kind of message will be changed between different parts and be sure that those messages are sent and received
Server:
import socket
import sys
host = socket.gethostname()
port = 9966
server_tcp = socket.socket()
server_tcp.bind((host, port))
server_tcp.listen(5)
n = 0
while n < 2:
c, addr = server_tcp.accept()
inData = c.recv(1024)
data = inData.decode()
texte = '';
print ('data received: {0}'.format(data))
if 'ABC' == data:
print ('sending back ok to the client')
texte = 'OK';
else:
print ('I did not get the right command ABC')
texte = 'FAIL';
#break
print("Respose: {0}".format(texte))
#ALWASY SEND THE RESPONSE IF YOUR CLIENT WAITS FOR IT
c.sendall(texte.encode(encoding = 'UTF-8'))
inData = c.recv(1024)
data = inData.decode()
print ('data received: {0}'.format(data))
if 'DEF' == data:
print ('sending back ok to the client')
texte = 'OK';
#n=c.send(texte.encode(encoding = 'UTF-8'))
else:
print ('I did not get the right command DEF')
texte = 'FAIL';
#break
print("Respose: {0}".format(texte))
#ALWASY SEND THE RESPONSE IF YOUR CLIENT WAITS FOR IT
c.sendall(texte.encode(encoding = 'UTF-8'))
print ('Closing Socket Client')
c.close()
n += 1
Client:
import socket
import sys
host = socket.gethostname()
port = 9966
client_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
rc = client_tcp.connect((host, port))
except:
print('Server not found')
#texte = "ABC"
texte = "DEF"
n=client_tcp.send(texte.encode(encoding = 'UTF-8'))
inData=client_tcp.recv(1024)
data = inData.decode()
print ("[" + data + "]")
if 'OK' == data:
print('good')
else:
print('bad')
#texte = "DEF"
texte = "ABC"
n=client_tcp.send(texte.encode(encoding = 'UTF-8'))
inData=client_tcp.recv(1024)
data = inData.decode()
print ("[" + data + "]")
if 'OK' == data:
print('good')
else:
print('bad')
client_tcp.close()
Client's output Order ABC DEF:
[OK]
good
[OK]
good
Client's output Order DEF ABC:
[FAIL]
bad
[FAIL]
bad
I created a HTTP proxy using this tutorial https://null-byte.wonderhowto.com/how-to/sploit-make-proxy-server-python-0161232/.
I am using this proxy with firefox browser. When I open a website in browser. The connection between firefox-proxy and proxy-webserver is successful and the proxy successfully receives data from webserver. But when I sent the data back to browser it doesn't render any page (I don't see webpage in browser). What may be the issue here ?
import socket, sys
from thread import *
try:
listening_port = int(raw_input("[*] Enter Listening Port Number: "))
except KeyboardInterrupt:
print "\n[*] User Requested An Interrupt"
print "[*] Application Exiting ..."
sys.exit()
max_conn = 20 #Max Connections in Queue
buffer_size = 262144 # Max socket Buffer size
def start():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # initiates socket
s.bind(('', listening_port)) # Bind socket for listen
s.listen(max_conn) # start listening for incoming connections
print "[*] Initializing Sockets ... Done"
print "[*] Sockets Binded succesfully ..."
print("[*] Server started succesfully [ %d ]\n" % (listening_port))
except Exception, e:
print "[*] Unable to initialize socket", e
sys.exit(2)
while 1:
try:
conn, addr = s.accept() # Accept connection From client browser
print "Connection accepted from browser"
data = conn.recv(buffer_size) # Receive CLient Data
print "Received request from browser"
start_new_thread(conn_string, (conn, data, addr)) # start a thread
except KeyboardInterrupt:
print "\n[*] Proxy Server Shutting down ..."
sys.exit(1)
s.close()
def conn_string(conn, data, addr):
# Client Browser Request Appears Here
try:
first_line = data.split('\n')[0]
url = first_line.split(' ')[1]
print "URL ", url
http_pos = url.find("://") # find the position of ://
if (http_pos == -1):
temp = url
else:
temp = url[(http_pos+3):] # get the rest of the URL
print "http pos, Temp", http_pos, temp
port_pos = temp.find(":") # Find the postion of port (if any)
webserver_pos = temp.find("/") # Find the end of the web server
if webserver_pos == -1:
webserver_pos = len(temp)
webserver = ""
port = -1
#print "Port pos, webserver_pos", port_pos, webserver_pos
if (port_pos == -1 or webserver_pos < port_pos): # default port
port = 80
webserver = temp[:webserver_pos]
else:
# Specific port
port = int((temp[(port_pos+1):])[:webserver_pos-port_pos-1])
webserver = temp[:port_pos]
# print "WEB server", webserver
print "Data extracted from request Request"
proxy_server(webserver, port, conn, addr, data)
except Exception, e:
pass
def proxy_server(webserver, port, conn, addr, data):
try:
print "starting connection towebserver"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#print "connecing host", webserver, port
s.connect((webserver, port))
print "connected"
#print "data", data
s.send(data)
print "Request sent"
while 1:
# Read reply or data to from end web server
reply = s.recv(buffer_size)
print "Reply Received ", reply
if (len(reply) > 0):
conn.send(reply) # send reply back to client
# Send notification to proxy Server [script itself]
dar = float(len(reply))
dar = float(dar / 1024)
dar = "%.3s" % (str(dar))
dar = "%s KB" % (dar)
print "[*] Request Done: %s => %s <=" % (str(addr[0]), str(dar))
else:
break
s.close()
conn.close()
print "Conn CLosed ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
except socket.error, (value, message):
print "Error", message
s.close()
conn.close()
sys.exit(1)
start()
This script is supposed to continuously read different rfid tags once, print out the tag number and send it to the remote xbee. However, it keeps reading tags in a continuous loop. I want it to read a tag once display the result and send it to the remote xbee, then wait for a different tag and repeat the process.
def main():
ann = as3992_api.AntennaDevice()
print "Firmware info: %s\nHardware info: %s" % ann.get_system_info()
print "Activating antenna"
ann.set_antenna_state(True)
print " Reading Tags:"
while True:
try:
for epc, rssi in ann.iter_epc_rssi():
#time.sleep(1)
print "---------------------------------------"
print "Scanning Tag..."
time.sleep(1)
print "Tag code epc:" +epc.encode("HEX"),rssi
#send tag info to remote xbee
xbee.tx_long_addr(frame='0x1', dest_addr=XBEE1_ADDR_LONG, data=epc.encode("HEX"))
print "---------------------------------------"
time.sleep(1)
print "Sending tag information to XBee 1 ..."
except KeyboardInterrupt:
ann.set_antenna_state(False)
break
if __name__ == "__main__":
main()
def main():
ann = as3992_api.AntennaDevice()
print "Firmware info: %s\nHardware info: %s" % ann.get_system_info()
print "Activating antenna"
ann.set_antenna_state(True)
print " Reading Tags:"
ok=[]
while True:
try:
for epc, rssi in ann.iter_epc_rssi():
if epc+rssi not in ok:
#time.sleep(1)
print "---------------------------------------"
print "Scanning Tag..."
time.sleep(1)
print "Tag code epc:" +epc.encode("HEX"),rssi
#send tag info to remote xbee
xbee.tx_long_addr(frame='0x1', dest_addr=XBEE1_ADDR_LONG, data=epc.encode("HEX"))
print "---------------------------------------"
time.sleep(1)
print "Sending tag information to XBee 1 ..."
ok.append( epc+rssi )
except KeyboardInterrupt:
ann.set_antenna_state(False)
break
I want to keep some file content loaded in memory so that it can be queried in retrived instantly.
In gearman worker, I am loading the file and put it in listening mode. While making request using gearman client, worker returns loaded content only once, next time client receives None
worker :
class GetLexiconFiles(object):
def __init__(self):
self.gm_worker = gearman.GearmanWorker(['localhost:4730'])
self.loadFiles()
self.gm_worker.register_task('load_db', self.task_listener_reverse)
#self.loadFiles()
#self.gm_worker.work()
def task_listener_reverse(self, gearman_worker, gearman_job):
k=float('inf')
#print "Started loading file"
self.input_text = self.input_text.split('\n')
print "Loading completed"
lexicon = defaultdict(list)
for i, line in enumerate(self.input_text):
#print "line is : ", line
if i >= k: break
#if i % 100000 == 0: print >>sys.stderr, i
try:
if line != '':
nl, dbs = line.split(' ', 1)
nl = int(nl)
dbs = self.str2obj(dbs)
lexicon[nl].append(dbs)
else:
pass
except:
print >>sys.stderr, 'could not parse line %r' % line
print traceback.format_exc()
continue
return json.dumps(lexicon)
if __name__ == '__main__':
GetLexiconFiles().gm_worker.work()
client :
def check_request_status(job_request):
if job_request.complete:
#data = json.loads(job_request.result)
print "Job %s finished! Result: %s - %s" % (job_request.job.unique, job_request.state, job_request.result)
elif job_request.timed_out:
print "Job %s timed out!"
elif job_request.state == JOB_UNKNOWN:
print "Job %s connection failed!"
gm_client = gearman.GearmanClient(['localhost:4730'])
tasks = [{'task': 'load_lexicon', 'data': 'This is testing sentence'}, {'task': 'load_db', 'data': 'This is db testing'}]
submitted_requests = gm_client.submit_multiple_jobs(tasks, background=False, wait_until_complete=False)
completed_requests = gm_client.wait_until_jobs_completed(submitted_requests)
print completed_requests[1].result
for completed_job_request in completed_requests:
check_request_status(completed_job_request)
self.input_text = self.input_text.split('\n')
With this line of code you are converting a string to a list of strings.
Since you save the result back in self.input_text the next time that that function gets called self.input_text will already be a list and it'll raise an exception.
I'm trying to create a little chat program that connect two (or more) computers, so I tried this :
import socket
tcpSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
tcpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
tcpSocket.bind(("0.0.0.0",8000))
tcpSocket.listen(3)
print "Waiting for a Client ... "
(client, (ip,sock)) = tcpSocket.accept()
print "Received connection from : ",ip
print "Starting ECHO output ..."
data = 'dump'
client.send("Enter you're name : ")
name=client.recv(1024)
name=name.strip()
while len(data) :
send_data = raw_input("Me : ")
try :
client.send("Server : "+send_data)
client.send("\n"+name+" : ")
except :
print "Connection lost !"
break
data = client.recv(2048)
data = data.strip()
print name+" : "+data
print "Closing connection ..."
client.close()
print "Shutting down server ..."
tcpSocket.close()
And it worked well, the only problem is that I can't connect more than one computer to the server! I tried with the thread module by using this fonction:
import socket
import thread
def thread_send() :
print "Received connection from : ",ip
print "Starting ECHO output ..."
data = 'dump'
client.send("Enter you're name : ")
name=client.recv(1024)
name=name.strip()
while len(data) :
send_data = raw_input("Me : ")
try :
client.send("Server : "+send_data)
client.send("\n"+name+" : ")
except :
print "Connection lost !"
break
data = client.recv(2048)
data = data.strip()
print name+" : "+data
tcpSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
tcpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
tcpSocket.bind(("0.0.0.0",8000))
tcpSocket.listen(5)
print "Waiting for a Client ... "
(client, (ip,sock)) = tcpSocket.accept()
for i in range(5) :
thread.start_new_thread(thread_send,())
while True :
pass
print "Closing connection ..."
client.close()
print "Shutting down server ..."
tcpSocket.close()
But it doesn't work :/
Below is an example of how you do it. Sorry, I have not tested this code nor ran it to check for any kind of syntax issue, this is just for giving an idea.
def thread_send(cli_sock):
data = 'dump'
cli_sock.send("Enter you're name : ")
name=cli_sock.recv(1024)
if len(name) == 0: ## If client disconnected or terminated
return
name=name.strip()
while len(data) :
send_data = raw_input("Me : ")
try :
cli_sock.send("Server : "+send_data)
cli_sock.send("\n"+name+" : ")
except :
print "Connection lost !"
break
data = client.recv(2048)
data = data.strip()
print name+" : "+data
serv_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serv_sock.bind(('localhost', 8080))
serv_sock.listen(1)
print "After listen...waiting for accept\n"
try:
while True:
client_sock, address = serv_sock.accept()
print "Connection accepted\n"
thread.start_new_thread(thread_send, (client_sock))
finally:
serv_sock.close()