“The connection was reset” on web browsers when trying to connect to a localhost socket server

 ̄綄美尐妖づ 提交于 2019-12-31 03:54:33

问题


I am trying to make a server in python using sockets that I can connect to on any web browser. I am using the host as "localhost" and the port as 8888.

When I attempt to connect to it, the stuff I want to be shown shows up for a split-second, and then it goes away with the browser saying "The connection was reset".
I've made it do something very simple to test if it still does it, and it does.

Is there a way to stop this?

import time
import socket
HOST = "localhost"
PORT = 8888

def function(sck):
    sck.send(bytes("test"),"UTF-8"))
    sck.close()

ssck=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ssck.bind((HOST,PORT))
ssck.listen(1)
while True:
    sck,addr=ssck.accept()
    function(sck)

回答1:


Probably the same problem as Perl: Connection reset with simple HTTP server, Ultra simple HTTP socket server, written in PHP, behaving unexpectedly, HTTP Server Not Sending Complete File To WGET, Firefox. Connection reset by peer?. That is you don't read the HTTP header from the browser but simply send your response and close the connection.




回答2:


tl;dr your function should be

def function(sck):
    sck.send(bytes("HTTP/1.1 200 OK\n\n<header><title>test page</title></header><body><h1>test page!</h1></body>"),"UTF-8"))
    sck.close()

With a server as simple as that, you're only creating a TCP socket.

HTTP protocols suggest that the client should ask for a page, something like:

HTTP/1.1 GET /somepath/somepage.html
Host: somehost.com
OtherHeader: look at the http spec

The response should then be:

HTTP/1.1 200 OK
some: headers

<header></header><body></body>


来源:https://stackoverflow.com/questions/33947908/the-connection-was-reset-on-web-browsers-when-trying-to-connect-to-a-localhost

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!