Chapter VIII of the socket network programming (5): client and server code bug fixes (code completion)

Previous position to write code, although we can perform, but there are many potential bug

  • Solve problems
    • Port Reuse: sometimes turned off the server port is still occupied because the port OS recovery takes time, this time there are 2 solutions:
      • .setsockopt way to achieve reuse port
      • The case of the Linux OS: Linux modify system settings
    • When the client sends an empty string, it will be stuck in recv step on the client, because the server can not receive things so it will not respond to client

      Principle: The application must send and receive data through the OS, it is essentially send and recv data and interact with their OS memory data. OS communication information is then processed in accordance with the protocol. When the client sends data, empty data through an additional header to be done to the server, but the server application to retrieve data from memory when the OS but nothing equivalent to the server did not receive stuff, so I do not It sends data to the client.

      • The need to avoid empty data from clients
    • Forced termination when the client (i.e., bi-directional connection conn socket object side are turned off),
      • Linux: unlimited server will entertain (null byte has been received in an infinite loop)
      • Windows will complain: ConnectionResetError

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)  

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

#5 收,发消息(传数据)
while True:
    try:  # windows的情况会报错,所以我们需要异常处理
        data = conn.recv(1024)
        if not data : break  # 避免服务端的死循环:Linux的情况下
        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/11298981.html