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

socket簡單通訊2

服務端

import socket,time
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()   #接收客戶端的連線
count = 0
while count < 10:
    
#ret = conn.recv(1024) ret = float(conn.recv(1024).decode("utf-8")) print(ret) ret_time = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(ret)) # if ret == "再見": # conn.send(bytes("再見",encoding="utf-8")) # break # info = input(">>>") conn.send(bytes(ret_time,encoding="
utf-8")) count += 1 # 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() #
關閉服務套接字(可選)
View Code

客戶端

import socket,time
sk = socket.socket()      #建立客戶套接字
sk.connect(("127.0.0.1",8080)) #嘗試連線服務
count = 0
while count < 10:
    time.sleep(2)
    info = bytes(str(time.time()),encoding="utf-8")
    sk.send(info)
    ret = sk.recv(1024).decode("utf-8")
    print(ret)
    count += 1
    # 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()
View Code