Chapter VIII of the socket network programming (4): plus communication cycle based on a simple socket (code completion)

On the basis of previous examples of communication, we add a communication cycle

server.py

import socket

phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  

phone.bind(('127.0.0.1',8080))  

phone.listen(5)  

print('starting...')  
conn, client_addr = phone.accept()  

#5 收,发消息(传数据)
while True:  # 循环通信:收,发消息
    data = conn.recv(1024)  # 服务端等待:收客户端来的信息
    print('客户端的数据',data)
    conn.send(data.upper())  # 服务端发信息

conn.close() 
phone.close()  

client.py

import socket

phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
 
phone.connect(('127.0.0.1',8080))  # 连接服务器的IP和端口

#3 发,收消息
while True:  # 循环通信:发,收消息
    msg = input('>>> : ').strip()
    phone.send(msg.encode('utf-8'))  # 客户端发信息
    data = phone.recv(1024)  # 客户端等待:收服务端来的信息
    print(data)

phone.close()

Guess you like

Origin www.cnblogs.com/py-xiaoqiang/p/11298972.html