python启动服务,并监听端口

import socket
import sys
import time
from urllib.parse import urlparse

def detect():
    try:
        s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)

        s.bind(('0.0.0.0',8999))
        s.listen(10)
    except socket.error as msg:
            print(msg)
            sys.exit(1)
    print("[",time.asctime(time.localtime(time.time())),"] Wait for Connection……")
    while True:
        sock,add = s.accept()
        buf = sock.recv(1024)
        msg =  str(buf)
        print("[",time.asctime(time.localtime(time.time())),"] ",str(add[0])+" msg:"+msg)
        if msg.__contains__("stop"):
             print("[",time.asctime(time.localtime(time.time())),"] server exit")
             exit(0)
        print("[",time.asctime(time.localtime(time.time())),"] server ready...")
        msg = '''HTTP/1.1 200 OK\r\nContent-Type: application/json; charset=utf-8\r\nDate: Fri, 11 Aug 2023 08:49:28 GMT\r\nContent-Length: 20\r\n\r\n{"status":"success"}'''
        sock.send(msg.encode('utf-8'))
        sock.close()

def recovery_listening():
    while 10:
        # time.sleep(5)
        detect()
recovery_listening()

你可能感兴趣的:(python,linux,服务器)