I'm trying to create a 2 way communication socket in python. The socket will listen for connections from the client until it gets the data formatted in string like this: 'PHONENUMBER|STATUS'. I will need to split that and convert it to json which will be sent via http request to a web api. When the api receives, it will handle the request and then it will return a status in json format which I will convert to string to return it to the client as string. I would like to have a professional opinion about my code and any additional ideas to what I would like to achieve would be appreciated.
import socket
import json
import requests
import httplib
HOST= '127.0.0.1'
PORT= 80
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Bind to adress
s.bind((HOST,PORT))
print ("Socket bound.")
#Start listening
s.listen(10)
print ("Socket Listening")
conn, addr = s.accept()
url = 'http://www.google.com'
while True:
data = conn.recv(1024)
dictionary = dict(item.split("|") for item in data .split(";"))
json = json.dumps(dictionary, ensure_ascii=False)
r = requests.get(url, data=json)
print r.text
1 Answer 1
This code does not compile, and has many bugs. Can you fix the errors in it?
url- =
is a syntax error.
I don't recommend calling a variable split
when you are using a method split
, it's confusing.
You did not use that variable named split
.
You did not define a variable message
.
print 'r.text'
should I suppose be print r.text
.
I'm not sure about data = conn.recv(1024)
, what will happen if a request is longer than 1024 bytes?
This code needs to be debugged, it is not ready for code review. But it seems like a nice idea, and structurally okay, a good start. I could help you debug it and get it working if you like.
-
\$\begingroup\$ Thanks, I formatted the text, it was all messed up. Now it can be reviewed \$\endgroup\$Alexander P.– Alexander P.2015年02月03日 14:29:25 +00:00Commented Feb 3, 2015 at 14:29
print r.text
needs to be indented same as the previous lines with six spaces (which is an unusual indent level, by the way - I suggest 4 or 8 spaces, or one tab). If this code works now, as you suggest, please provide an example session using e.g. telnet or a test program: what data you send to it, and what data you expect it to send back after talking to google. \$\endgroup\$