今天实现在客户端和服务端之间进行持续的通信
客户端代码
import socket ip_port = ("127.0.0.1",3000) sk = socket.socket() sk.connect(ip_port) sk.sendall(bytes("请求占领地球",encoding="utf-8")) server_replay = sk.recv(1024) print(str(server_replay,encoding="utf-8")) while True: client_input = input(">>client:").strip() sk.sendall(bytes(client_input,encoding="utf-8")) server_replay = sk.recv(1024) print(">>server:",str(server_replay,encoding="utf-8")) sk.close()
服务端代码
import socket ip_bind = ("127.0.0.1",3000) sk = socket.socket() sk.bind(ip_bind) sk.listen(5) while True: print("server is waiting.....") conn,add = sk.accept() client_data = conn.recv(1024) print(str(client_data,encoding="utf-8")) conn.sendall(bytes("不要不要回答,不要回答,不要回答",encoding="utf-8")) while True: try: client_data = conn.recv(1024) print(">>client:",str(client_data,encoding="utf-8")) except Exception: print("connection is failed") break server_reply = input("server>>:").strip() conn.sendall(bytes(server_reply,encoding="utf-8")) conn.close()
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/20889.html