服务端代码:
importsocketimporttimeprint("服务端开启") # 创建套接字mySocket=socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 设置IP和端口# host = socket.gethostname()host='127.0.0.1'port=3333# bind绑定该端口mySocket.bind((host, port)) # 监听mySocket.listen(10) whileTrue: # 接收客户端连接print("等待连接....") client, address=mySocket.accept() print("新连接") print("IP is %s"%address[0]) print("port is %d\n"%address[1]) whileTrue: # 发送消息msg="连接成功"client.send(msg.encode(encoding='utf-8')) print("发送完成") print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))) # 格式化时间戳为标准格式ifmsg=="EOF": breakifmsg=="quit": client.close() mySocket.close() print("程序结束\n") exit() # 读取消息msg=client.recv(1024) print("服务端接收:", msg.decode("utf-8")) # 把接收到的数据进行解码print("读取完成") ifmsg==b"EOF": breakifmsg==b"quit": client.close() mySocket.close() print("程序结束\n") exit()
客户端代码:连接后保持连接
importsocketprint("客户端开启") # 创建套接字mySocket=socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 设置ip和端口# host = socket.gethostname()host='127.0.0.1'port=3333try: mySocket.connect((host, port)) ##连接到服务器print("连接到服务器") except: ##连接不成功,运行最初的ipprint('连接不成功') while1: # 接收消息msg=mySocket.recv(1024) print("客户端接收:%s"%msg.decode("utf-8")) # 把接收到的数据进行解码print("读取完成") ifmsg==b"EOF": breakifmsg==b"quit": mySocket.close() print("程序结束\n") exit() # 发送消息msg=input("客户端发送:") mySocket.send(msg.encode(encoding='utf-8')) print("发送完成") ifmsg=="EOF": breakifmsg=="quit": mySocket.close() print("程序结束\n") exit() print("程序结束\n")
客户端代码:发送后自动断开连接
importsocketsk=socket.socket() sk.connect(('127.0.0.1',3333)) msg=sk.recv(1024).decode('utf-8') # 最多接受1024字节print(msg) sk.send('你好'.encode('utf-8')) #sk.close()