日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python3.6 websocket异步高并发_Python3.6 websocket开发

發布時間:2024/9/19 python 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python3.6 websocket异步高并发_Python3.6 websocket开发 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

message_queues ={}

client_socket_fd_map={}defstart_socket_select_server():

sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)

sock.bind(('0.0.0.0', 8002))

sock.listen(5)print("WebSocket 服務器啟動成功 監聽IP", ('127.0.0.1', 8002))

sock.setblocking(False)

inputs=[sock, ]

outputs=[]whileTrue:

readable, writeable, exceptional=select.select(inputs, outputs, inputs)#print('select finish, inputs size:%d, outputs size:%d' % (len(inputs), len(outputs)))

for s inreadable:if s issock:

conn, client_addr=s.accept()print("new connection from", client_addr)

conn.setblocking(False)

inputs.append(conn)

message_queues[conn]=queue.Queue()else:if s not inoutputs:#第一次 表示 websocket的握手

data = s.recv(1024)ifdata:print('received [%s] from %s' %(data, s.getpeername()[0]))#message_queues[s].put(data)

headers=get_headers(data)

response_tpl= "HTTP/1.1 101 Switching Protocols\r\n"\"Upgrade: websocket\r\n"\"Connection: Upgrade\r\n"\"Sec-WebSocket-Accept: %s\r\n"\"WebSocket-Location: ws://%s%s\r\n\r\n"sha1=hashlib.sha1()

magic_string= "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"value= headers['Sec-WebSocket-Key'] +magic_string

sha1.update(value.encode('utf-8'))

ac=base64.b64encode(sha1.digest())

response_str= response_tpl %(

ac.decode('utf-8'), headers['Host'], headers['url'])

s.send(bytes(response_str, encoding='utf-8'))

# 這里將文件描述符返回給瀏覽器 瀏覽器可以在接下來的http請求中帶上這個參數 服務端就可以向這個文件描述符中寫入信息返回給指定瀏覽器

fileno_dict_str= '{"type":1, "body":%s}' %s.fileno()

message_queues[s].put(fileno_dict_str)if s not inoutputs:

outputs.append(s)

client_socket_fd_map[s.fileno()]=selse:#表示客戶端已經斷開

print("~~~~~~~~~~~client [%s] closed" %s)if s inoutputs:

outputs.remove(s)delmessage_queues[s]delclient_socket_fd_map[s.fileno()]

inputs.remove(s)

s.close()else:#websocket 通信

data = s.recv(8096)ifdata:pass

else:#表示客戶端已經斷開

print("-------------client [%s] closed" %s)if s inoutputs:

outputs.remove(s)delmessage_queues[s]delclient_socket_fd_map[s.fileno()]

inputs.remove(s)

s.close()for s inwriteable:try:

next_msg=message_queues[s].get_nowait()exceptqueue.Empty:pass

else:

send_msg(s, next_msg)

總結

以上是生活随笔為你收集整理的python3.6 websocket异步高并发_Python3.6 websocket开发的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。