码迷,mamicode.com
首页 > 其他好文 > 详细

socket链接循环

时间:2018-06-16 01:03:12      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:art   erro   port   ror   imp   tin   数据   linux   nbsp   

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()


socket链接循环

标签:art   erro   port   ror   imp   tin   数据   linux   nbsp   

原文地址:https://www.cnblogs.com/fmgao-technology/p/9189380.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!