1. 程式人生 > >學習筆記-- Python網絡編程

學習筆記-- Python網絡編程

print listen 接收消息 accept rec 發送消息 spa color python

TCP編程-- server

 1 import socket, threading, time
 2 
 3 def dealClient(sock, addr):
 4     print(Accept new connection from %s:%s... % addr)
 5     sock.send(bHello, I am server!)  # 給client端發送數據
 6     while True:
 7         data = sock.recv(1024)  # 接收client發過來的數據
 8         time.sleep(1)
 9         if
not data or data.decode(utf-8) == exit: 10 break 11 print(-->> %s ! % data.decode(utf-8)) 12 sock.send((Loop_Msg: %s ! % data.decode(utf-8)).encode()) # 發送數據給client 13 sock.close() 14 print(Connection from %s:%s closed % addr) 15 16 if __name__
== __main__: 17 # 創建socket並綁定IP 18 s = socket.socket() 19 s.bind((127.0.0.1, 9999)) 20 s.listen() # 啟用監聽 21 print(Waiting for connection...) 22 while True: 23 sock, addr = s.accept() # 接收一個新的連接 24 t = threading.Thread(target = dealClient, args = (sock, addr)) #
創建新的線程來處理TCP連接 25 t.start()

TCP編程-- client

1 import socket
2 
3 s = socket.socket()
4 s.connect((127.0.0.1, 9999))  # 建立連接
5 print(-->> + s.recv(1024).decode(utf-8)) # 接收消息
6 s.send(bHello, I am a client)
7 print(-->> + s.recv(1024).decode(utf-8))
8 s.send(bexit)  # 發送消息
9 s.close()

代碼摘自 Python爬蟲開發與項目實戰-- 機械工業出版社

學習筆記-- Python網絡編程