服务端
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() #关闭服务套接字(可选)
客户端
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()