day08_02 SocketServer多次通信
作者:互联网
socket_server.py
__author__ = "Alex Li"
# -*-coding:utf-8-*-
# 服务器端
import socket
server = socket.socket()
server.bind(('localhost', 6969)) # 绑定要监听端口
server.listen(5) # 监听
print("我要开始等电话了")
while True:
# conn就是客户端连过来而在服务器端为其生成的一个连接实例
conn, addr = server.accept() # 等电话打进来,有客户端进来就继续向下执行
print(conn, addr)
print("client电话来了")
count = 0
while True:
data = conn.recv(1024)
print("recv:", data)
if not data:
print("client has lost...")
break
# 向客户端推送数据
conn.send(data.upper())
count += 1
print(count)
# 服务器只处理10个数据,然后会出现死循环
if count == 10:
break
if count == 10:
break
server.close()
socket_client.py
__author__ = "Alex Li"
# 客户端
import socket
client = socket.socket() # 声明socket类型,同时生成socket连接对象
client.connect(('localhost', 6969))
while True:
msg = input(">>:").strip()
if len(msg) == 0:
continue
client.send(msg.encode("utf-8"))
data = client.recv(10240)
print("客户端接收到服务器端,转换后的数据:", data.decode())
# 客户端关闭时,服务器dau端也会收到心跳检测失效
client.close()
标签:02,day08,socket,SocketServer,server,client,print,data,客户端 来源: https://www.cnblogs.com/netflix/p/14855239.html