-
-
Save leehambley/fa634f91936b1d30422e3af96ba2eec5 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
# import socket programming library | |
import socket | |
import time | |
from datetime import datetime | |
# import thread module | |
from _thread import * | |
import threading | |
# thread function | |
def threaded(c): | |
while True: | |
# data received from client | |
data = c.recv(4024) | |
if not data: | |
print(datetime.now(), ' Bye') | |
# lock released on exit | |
break | |
# reverse the given string from client | |
print(datetime.now(), "from client: ", data) | |
# send back reversed string to client | |
if 'healthz' in str(data): | |
rsp_head = ( | |
"HTTP/1.1 200 OK\r\n" | |
"Content-Length: 0\r\n" | |
"cache-control: max-age=50\r\n" | |
"Content-Type: text/plain\r\n\r\n" | |
) | |
c.send(bytes(rsp_head, "utf-8")) | |
break | |
else: | |
time.sleep(10) | |
rsp_head = ( | |
"HTTP/1.1 500 notOK\r\n" | |
"Content-Length: 1\r\n" | |
"Content-Type: text/plain\r\n\r\n" | |
"1" | |
) | |
c.send(bytes(rsp_head, "utf-8")) | |
# connection closed | |
c.close() | |
def Main(): | |
host = "" | |
# reserve a port on your computer | |
# in our case it is 12345 but it | |
# can be anything | |
port = 3100 | |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) | |
s.bind((host, port)) | |
print("socket binded to port", port) | |
# put the socket into listening mode | |
s.listen(10) | |
print(datetime.now(), " socket is listening") | |
# a forever loop until client wants to exit | |
while True: | |
# establish connection with client | |
c, addr = s.accept() | |
# lock acquired by client | |
print(datetime.now(), ' Connected to :', addr[0], ':', addr[1]) | |
# Start a new thread and return its identifier | |
start_new_thread(threaded, (c,)) | |
s.close() | |
if __name__ == '__main__': | |
Main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment