Web靜態伺服器 非堵塞模式

2021-09-18 09:08:00 字數 1477 閱讀 4117

#coding=utf-8

from socket import

*import time

# 用來儲存所有的新鏈結的socket

g_socket_list =

list()

defmain()

: server_socket = socket(af_inet, sock_stream)

server_socket.setsockopt(sol_socket, so_reuseaddr ,1)

server_socket.bind((''

,7890))

server_socket.listen(

128)

# 將套接字設定為非堵塞

# 設定為非堵塞後,如果accept時,恰巧沒有客戶端connect,那麼accept會

# 產生乙個異常,所以需要try來進行處理

server_socket.setblocking(

false

)while

true

:# 用來測試

time.sleep(

0.5)

try:

newclientinfo = server_socket.accept(

)except exception as result:

pass

else

:print

("乙個新的客戶端到來:%s"

%str

(newclientinfo)

) newclientinfo[0]

.setblocking(

false

)# 設定為非堵塞

for client_socket, client_addr in g_socket_list:

try:

recvdata = client_socket.recv(

1024

)if recvdata:

print

('recv[%s]:%s'%(

str(client_addr)

, recvdata)

)else

:print

('[%s]客戶端已經關閉'

%str

(client_addr)

) client_socket.close(

) g_socket_list.remove(

(client_socket,client_addr)

)except exception as result:

pass

print

(g_socket_list)

# for test

if __name__ ==

'__main__'

: main(

)

Python Web靜態伺服器 非堵塞模式

coding utf 8 from socket import import time 用來儲存所有的新鏈結的socket g socket list list def main server socket socket af inet,sock stream server socket.setso...

非阻塞web靜態伺服器

單程序但鏈結非阻塞web靜態伺服器 author bre athy contact productware pycharm file 單程序但鏈結非阻塞web靜態伺服器.py time 2019 11 9 5 33 import socket,re defservice client new soc...

web靜態伺服器 epool

以下 支援http的長連線,即使用了content length import socket import time import sys import re import select class wsgiserver object 定義乙個wsgi伺服器的類 def init self,port...