首页 > 代码库 > python3 socket循环

python3 socket循环

技术分享
 1 import socket
 2 phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #买手机
 3 phone.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) #就是它,在bind前加
 4 phone.bind((127.0.0.1,8080)) #插入卡
 5 phone.listen(5) #开机
 6 while True: #链接循环
 7     conn,addr=phone.accept()
 8     print(client :,addr)
 9     while True: #通讯循环
10         try:
11             data=http://www.mamicode.com/conn.recv(1024)
12             if not data:break #针对linux,客户端断开链接的异常处理
13             print(from client msg :%s %data)
14             conn.send(data.upper())
15         except Exception:
16             break
17     conn.close()
18 phone.close()
server
技术分享
import socket
client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

client.connect((192.168.12.110,8080)) #拨通电话

while True:
    msg=input(>>: )
    if not msg:continue
    client.send(msg.encode(utf-8)) #客户端发消息
    print(====>has send)

    data=client.recv(1024) #客户端收消息
    print(=====>has recv)
    print(data)
client.close() #关闭
client

 

python3 socket循环