Chapter VIII of the socket network programming (6): plus connected circulation (Code Completion)

Previous continues, we continue to improve the program

Until now, we have stopped the client, the server will end together. But think about it, it does not really end services, can only serve as a client so we need to be able to accept access to multiple clients (temporarily we do not study concurrent programming, let us first deal with a can a)

server.py

import socket

phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
phone.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
phone.bind(('127.0.0.1',8080))  
phone.listen(5)  # 挂起的客户端最多有5个

print('starting...')  

while True:  # 循环连接建立以及处理的部分
    conn, client_addr = phone.accept()  
    
    #5 收,发消息(传数据)
    while True:
        try:
            data = conn.recv(1024)
            if not data : break
            print('客户端的数据',data)
            conn.send(data.upper())
        except ConnectionResetError:
            break
        
    conn.close()
     
phone.close()  

client.py

import socket

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

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

#3 发,收消息
while True:
    msg = input('>>> : ').strip()
    if not msg : continue
    phone.send(msg.encode('utf-8'))
    data = phone.recv(1024)
    print(data)

phone.close()

Guess you like

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