socket链接循环

时间:2023-01-18 13:33:51

server------------------------
#!/usr/bin/env python
# encoding: utf-8  
# Date: 2018/6/5

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', 8081))
phone.listen(5)

print('starting.......')
while True:  # 链接循环,保证客户端停止,服务端不停止,但是不支持并发
    conn, client_addr = phone.accept()
    print(client_addr)

while True:
        try:  # window异常捕获
            data = conn.recv(1024)
            if not data:  # 适用于linux
                break  # 客户端断掉,发送空过来
            print('客户端的数据', data)
            conn.send(data.upper())
        except ConnectionResetError:
            break
    conn.close()
phone.close()
client1--------------------------
#!/usr/bin/env python
# encoding: utf-8  
# Date: 2018/6/5

import socket

phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
phone.connect(('127.0.0.1', 8081))

while True:
    msg = input('>>>').strip()
    if not msg:continue
    phone.send(msg.encode('utf-8')) # 应用程序发给操作系统,操作系统调用网卡
    data = phone.recv(1024)
    print(data.decode('utf-8'))

phone.close()

client2--------------------

#!/usr/bin/env python
# encoding: utf-8  
# Date: 2018/6/5

import socket

phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
phone.connect(('127.0.0.1', 8081))

while True:
    msg = input('>>>').strip()
    if not msg:continue
    phone.send(msg.encode('utf-8')) # 应用程序发给操作系统,操作系统调用网卡
    data = phone.recv(1024)
    print(data.decode('utf-8'))

phone.close()