简体   繁体   English

如何从 python 发送正确的 http 响应?

[英]How to send correct http response from python?

I have an index.html file, which has some javascript in it.我有一个 index.html 文件,里面有一些 javascript。 The script is basicly creating a WebSocket.该脚本基本上是创建一个 WebSocket。 I want it to connect to a server which has a python script running, to send and HTTP response for the to communicate.我希望它连接到运行 python 脚本的服务器,以发送和 HTTP 响应以进行通信。 I'm not sure if this is even possible, im quite new in networking so im still learning我不确定这是否可能,我在网络方面很新,所以我还在学习

Javascript: Javascript:

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

Python: 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.我没有“200 OK”的原因是因为这会出错。

The getData() gets called whenewer a button is pressed in html.在 html 中按下按钮时调用 getData()。 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) (.js 文件中的 html 除外)

Just guessing but after header there must be a blank line只是猜测,但在 header 之后必须有一个空行

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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