------------------------------------------------服務端代碼--------------------------------------socket
__author__ = "託尼老師" """ 即時通信原理 @@@ 服務端代碼 """ from socket import * import threading ip = '0.0.0.0' port =8888 # 定義 socket 參數 Server = socket(AF_INET,SOCK_STREAM) Server.bind((ip,port)) Server.listen() print("[*] SocketServer 正在監聽...") # 接受函數 def recvs(): while 1: print(' [*] 客戶端說: %s '% client.recv(1024).decode('utf-8')) #發送函數 def sends(): while 1: say = bytes(input(' [*] 我說: ') , encoding='utf-8') client.send(say) # 堵塞接受請求 client,client_ip = Server.accept() print(client_ip[0] +':'+str(client_ip[1])+' 鏈接成功!' ) # 建立接受線程 receive = threading.Thread(target =recvs ,args=() ) receive.start() # 建立發送線程 send = threading.Thread(target =sends ,args=() ) send.start()
------------------------------------------------客戶端代碼--------------------------------------ide
__author__ = "託尼老師" """ 即時通信原理 @@@ 客戶端代碼 """ from socket import * import threading ip,port ='127.0.0.1',8888 Client = socket(AF_INET,SOCK_STREAM) Client.connect((ip,port)) def sends() -> '發送函數': while 1: say = bytes(input("[*]我說: "),encoding='utf-8') Client.send(say) def recvs() -> '接受函數': while 1: print('[*] 服務端說: %s ' % Client.recv(1024).decode('utf-8')) receive = threading.Thread(target =recvs ,args=() ) receive.start() # 建立發送線程 send = threading.Thread(target =sends ,args=() ) send.start()
先執行 服務端代碼,再執行客戶端代碼,能夠實現基本通信功能。僅供參考!歡迎指出優化!函數