简体   繁体   中英

How to send correct http response from python?

I have an index.html file, which has some javascript in it. The script is basicly creating a WebSocket. I want it to connect to a server which has a python script running, to send and HTTP response for the to communicate. I'm not sure if this is even possible, im quite new in networking so im still learning

Javascript:

    function getData(){
        var socket = new WebSocket("ws:my server's ip:6474");
        socket.onopen = () => socket.send("Hello, world!");
    }

Python:

import socket

serverSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
serverSock.bind(('0.0.0.0', 6474))
serverSock.listen(1)

while True:
     sock, addr = serverSock.accept()
     sock.send('HTTP/1.1\nContent-Type: text/html\n')
     data = sock.recv(1024)
     print(data.decode('utf-8').rstrip())

The reason I dont have '200 OK' is because that gives an error.

The getData() gets called whenewer a button is pressed in html. That works correctly. I get no errors but I don't see any text appearing on the server. (except the html from the.js file)

Just guessing but after header there must be a blank line

sock.send('HTTP/1.1\nContent-Type: text/html\n\n')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM