1、代码
import socket
def main():
# 创建套接字连接,返回tcpSocket对象
tcpServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定端口
tcpServer.bind(("192.168.163.1", 1227))
# 开启监听
tcpServer.listen(10)
while True:
try:
# 等待链接
print("等待链接")
sock, addr = tcpServer.accept()
print("%s链接成功!" % str(addr))
except:
print("链接失败")
# 接收客户端消息
# recData = sock.recvfrom(1024)
# print("%s \n %s" % (recData[1][1].decode("gbk"), recData[0].decode("gbk")))
while True:
try:
recData = sock.recv(1024)
except ConnectionAbortedError:
print("客户端关闭,等待新的客户端连接...")
break
print("%s" % recData.decode("gbk"))
# 给客户端发送消息
# sock.send(("收到消息:" + recData[0].decode("gbk")).encode("gbk"))
sock.send(("收到消息:" + recData.decode("gbk")).encode("gbk"))
# 关闭套接字
sock.close()
tcpServer.close()
if __name__ == "__main__":
main()
2、思考:
- 如何退出外层while循环?