import socket
def handle_client(socket_con):
"""
接收來自用戶端的請求,并接收請求封包,解析,傳回
"""
# 伺服器接收用戶端的請求封包
request = socket_con.recv(4096).decode()
print(request)
# 伺服器拼接響應封包并回複
response_line = 'HTTP/1.1 200 OK\r\n'
response_head = 'Server:skylark 2.0\r\n'
response_head += 'Content-Type:text/html;charset=utf-8\r\n'
response_body = '這是顯示的内容!\r\n'
response = response_line + response_head + '\r\n' + response_body
socket_con.send(response.encode())
socket_con.close()
def main():
# 伺服器建立負責監聽的socket
socket_listen = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 設定端口重用
socket_listen.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
# 綁定監聽端口
socket_listen.bind(('', 8888))
# 設定監聽隊列
socket_listen.listen(128)
# 通過循環不同的接受請求
while True:
# accept() 傳回元組 (socket object, address info)
socket_con, socket_con_adds = socket_listen.accept()
# 列印提示資訊
print('用戶端:',socket_con_adds,'連接配接成功!')\
# 使用函數處理用戶端發送的資訊
handle_client(socket_con)
if __name__ == '__main__':
main()