实现服务端可以对多个客户端提供服务
服务端:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
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', 8090))
phone.listen(10)
while True: # 连接循环
connt , client = phone.accept()
print('starting ....')
print(client)
while True: # 通信循环
try:
data = connt.recv(1024)
if not data :continue # 适用于Linux 操作系统
print( data.decode('utf-8'))
connt.send(data.upper())
except ConnectionResetError: # 适用于windows操作系统
break
connt.close()
phone.close()
客户端:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
phone1 = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
phone1.connect(('127.0.0.1',8090))
while True:
msg = input('>>>:').strip()
if not msg:continue
phone1.send(msg.encode('utf-8'))
data1 =phone1.recv(1024)
print(data1.decode('utf-8'))
phone1.close()