服務端:(server1)python
import socket sk = socket.socket() # 註冊主機 sk.bind( ("127.0.0.1",9000) ) # 參數是元組 # 開啓監聽 sk.listen() # 三次握手 # conn,addr = sk.accept() ''' conn: <socket.socket fd=480, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 9000), raddr=('127.0.0.1', 60879)> addr: ('127.0.0.1', 60879) ''' # print(conn,addr) while True: conn,addr = sk.accept() while True: msg = conn.recv(1024) print(msg.decode("utf-8")) # 服務器發消息 message = input("我要發的數據:>>>") conn.send(message.encode("utf-8")) if message == "q": break # 四次揮手 conn.close() # 退還端口 sk.close()
客戶端:(client1)服務器
import socket sk = socket.socket() sk.connect( ("127.0.0.1",9000) ) while True: message = input(">>>:") sk.send(message.encode("utf-8")) # 接收服務器發過的消息 res = sk.recv(1024) if res == b"q": break print(res.decode("utf")) sk.close()
服務端:(server2)socket
# 服務器 import socketserver import socket class MyServer(socketserver.BaseRequestHandler): def handle(self): # 自定義的邏輯... print("----> 執行這句話") # print(self.request) # print(self.client_address) conn = self.request while True: # 接收消息 msg = conn.recv(1024) print(msg.decode("utf-8")) # pass conn.send(b'world') # 生成一個對象 # ThreadingTCPServer( "ip端口號" ,"自定義的類" ) server = socketserver.ThreadingTCPServer( ("127.0.0.1",9000) , MyServer ) # 循環調用 server.serve_forever() ''' try: # lst = [1, 2, 3] # print(lst[99]) print(333) finally: print(1) print(2) ''' """ try .. finally .. 不論try 代碼塊裏面的代碼是否是報錯, 都會執行finally這個代碼塊中的內容. 做用:正常狀況,若是報錯,後面的代碼一概不執行, 可是特殊條件下,又必須在報錯的行爲中,執行某些代碼, 那麼這樣的代碼加到finally當中 """
客戶端: client2spa
# 客戶端 import socket sk = socket.socket() sk.connect( ("127.0.0.1",9000) ) while True: # 發消息 sk.send(b"hello") # 接收服務器消息 msg = sk.recv(1024) print(msg.decode("utf-8")) sk.close()