1. 程式人生 > >socket簡單通訊

socket簡單通訊

#服務端
import
socket from socket import SOL_SOCKET,SO_REUSEADDR sk = socket.socket() #建立服務端socket套接字 sk.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) #解決地址和埠被佔用的情況 sk.bind(("127.0.0.1",8080)) #繫結伺服器地址,埠號 sk.listen() #監聽 等待訊息 conn,adree = sk.accept() #接收客戶端的連線 while 1: ret = conn.recv(1024).decode("utf-8")
print(ret) if ret == "再見": conn.send(bytes("再見",encoding="utf-8")) break info = input(">>>") conn.send(bytes(info,encoding="utf-8")) # ret = conn.recv(1024) #接收客戶端資訊 引數一般為1024的整數倍 # print(ret) # conn.send(b"server") #向客戶端傳送訊息 # ret = conn.recv(1024)
# print(ret.decode("utf-8")) # conn.send(bytes("來吧來吧!",encoding="utf-8")) conn.close() #關閉客戶連線 sk.close() #關閉服務套接字(可選)
#客戶端
import
socket sk = socket.socket() #建立客戶套接字 sk.connect(("127.0.0.1",8080)) #嘗試連線服務 while 1: info = input(">>>") sk.send(bytes(info,encoding
="utf-8")) ret = sk.recv(1024).decode("utf-8") print(ret) if ret == "再見": sk.send(bytes("再見",encoding="utf-8")) break # sk.send(b"client") # ret = sk.recv(1024) # print(ret) # sk.send(bytes("約會不?",encoding="utf-8")) # ret = sk.recv(1024) # print(ret.decode("utf-8")) sk.close()