-----客户端
1 #客户端 2 import socket 3 4 client = socket.socket()#相当于声明socket类型,同时生成socket连接对象 5 client.connect(('localhost',6969)) 6 7 while True: 8 msg = input(">>:").strip() 9 #client.send(b"Hello World!") 10 client.send(msg.encode("UTF-8")) 11 data = client.recv(1024) 12 #print("recv:",data) 13 print("recv:",data.decode()) 14 15 client.close()
------服务端
1 #服务器端 2 import socket 3 4 server = socket.socket() 5 server.bind(("localhost",6969))#绑定要监听的端口 6 server.listen()#监听 7 8 print("我要开始等电话了") 9 10 while True: 11 conn,addr = server.accept()#等电话打进来 12 print(conn,addr) 13 14 print("电话来了") 15 while True: 16 data = conn.recv(1024) 17 print("recv:",data) 18 if not data: 19 print("client has lost...") 20 break 21 conn.send(data.upper()) 22 23 server.close()