Created
February 26, 2018 04:55
-
-
Save vimiix/eb35c39ff9bf8f043b6d7f48c01c40c3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding:utf-8 | |
import socket | |
EOL1 = "\n\n" | |
EOL2 = "\n\r\n" | |
body = """Hello World! <h1> Simple socket server</h1>""" | |
response_params = [ | |
'HTTP/1.0 200 OK', | |
'Date: Sat, 10 jun 2017 12:12:21 GMT', | |
'Content-Type: text/html; charset=utf-8', | |
'Content-Length: {0}\r\n'.format(len(body)), | |
body, | |
] | |
response = '\r\n'.join(response_params).encode() | |
def handle_connection(conn, addr): | |
request = "" | |
while EOL1 not in request and EOL2 not in request: | |
request += conn.recv(1024).decode() | |
conn.send(response) | |
conn.close() | |
def main(): | |
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
serversocket.bind(('127.0.0.1', 5555)) | |
serversocket.listen(1) | |
print('http://127.0.0.1:5555') | |
try: | |
while True: | |
conn, addr = serversocket.accept() | |
handle_connection(conn, addr) | |
finally: | |
serversocket.close() | |
if __name__ == "__main__": | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment