2

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
    You are aware that the browser expects your server to talk in HTTP? – spectras Nov 26 '15 at 22:38
  • What happens if you respond with a HTTP(-like) response? Like `HTTP/1.1 200 OK\nConnection: close\n\ntest` – Felk Nov 26 '15 at 22:39
  • Sorry, I wanted to just get it as simple as possible to get the main stuff across. It still does it with the headers there too. –  Nov 26 '15 at 22:42
  • Well, proper implementation of HTTP is not simple. If you want your project to be as simple as possible, I'd recommend using a light http lib, for instance [python's http.server](https://docs.python.org/3/library/http.server.html) or a lightweight framework such as [Flask](http://flask.pocoo.org/). – spectras Nov 26 '15 at 22:45
  • Felk, when I try that, it doesn't work at all. Rather than showing it for a split second, it just says "The connection was reset" –  Nov 26 '15 at 22:52

2 Answers2

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.

Community
  • 1
  • 1
Steffen Ullrich
  • 114,247
  • 10
  • 131
  • 172
  • For your local test purposes just `sck.recv(2**14)` will work (most of the time). An actual webserver would have to ensure to read the whole message. – Felk Nov 26 '15 at 22:59
  • Thank you very much Felk, that was what I needed. :) –  Nov 26 '15 at 23:10
0

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>
Neil Twist
  • 1,099
  • 9
  • 12