I'm newbie to JavaScript and AJAX here. Also new to web communications in general.
I'm trying to create a dynamically updating webpage that communicates to a Python server. I have been testing everything locally and so far all works.. I think.
The Python server serves "page.html" on localhost port 8000. The HTML page uses AJAX and XMLHttpRequest to POST data to the server. I can send data to the server just fine.
Here's the problem: my server indicates that for each post a new client port is opened. This scares me as I'm used to TCP sockets where communication occurs on a single port.
Here's the server code (server.py):
import cgi
import http.server
import urllib
import socketserver
class ServerHandler(http.server.SimpleHTTPRequestHandler):
def do_POST(self):
ctype, pdict = cgi.parse_header(self.headers['content-type'])
length = int(self.headers['content-length'])
postvars = urllib.parse.parse_qs(self.rfile.read(length).decode('utf-8'))
ip, port = self.client_address
print(ip, "@", port, "-->", postvars)
def start_server():
httpServer = socketserver.TCPServer(("", 8000), ServerHandler)
httpServer.serve_forever()
if __name__ == "__main__":
start_server()
Here's the HTML code (page.html):
<html>
<head></head>
<body>
<script type="text/javascript">
function send_receive() {
var http = new XMLHttpRequest();
var data = document.test_form.data.value;
var params = "data=" + data.toString();
http.open("POST", "page.html", true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.send(params);
}
</script>
<form name=test_form>
Data: <input type="text" name="data" value="1">
<input type=button onClick="send_receive();" value="Send"><br /><br />
</form>
</body>
</html>
Here's the server output after sending 1 to 6 on the page.
127.0.0.1 @ 52884 --> {'data': ['1']}
127.0.0.1 @ 52885 --> {'data': ['2']}
127.0.0.1 @ 52886 --> {'data': ['3']}
127.0.0.1 @ 52887 --> {'data': ['4']}
127.0.0.1 @ 52888 --> {'data': ['5']}
127.0.0.1 @ 52889 --> {'data': ['6']}
To test launch server.py, then go to a browser and type in
http://localhost:8000/page.html OR http://127.0.0.1:8000/page.html
As you can see the port increments for each POST. Is there anything I'm doing wrong? I feel like the XHR is lingering and it needs to be closed, but from what I've read online, apparent creating a new XHR is necessary for each POST. Thanks!