您好,登錄后才能下訂單哦!
server端
import sys,socket,time,gevent
from gevent import socket, monkey
monkey.patch_all()#卡住每個進程
def server(port):
s = socket.socket()
s.bind(('0.0.0.0', port))
s.listen(500)
while True:
cli, addr = s.accept()
gevent.spawn(handle_request, cli)#起協程 把cli連接傳給handle_request 遇到IO阻塞就切換
def handle_request(conn):# 類似socketserver的handle方法
try:
while True:
data = conn.recv(1024)
print("recv:", data)
conn.send(data)
if not data:
break #關閉客戶端
except Exception as ex:#打印異常
print(ex)
finally:
conn.close()
if __name__ == '__main__':
server(8001)
client端
import socket
HOST = 'localhost' # The remote host
PORT = 8001 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
while True:
msg = bytes(input(">>:"), encoding="utf8") #轉成bytes類型
if not msg:continue #輸入為空 跳出循環又從第1行開始循環
s.sendall(msg)
data = s.recv(1024)
# print(data)
print('Received', repr(data))#repr格式化輸出
s.close()
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。