简体   繁体   English

Python套接字重新连接

[英]Python socket reconnecting

I have a socket program and I want to keep the connection running all the time, if someone disconnects I want to start listening to a new connection and keep the program running. 我有一个套接字程序,我想一直保持连接运行,如果有人断开连接,我想开始监听新的连接并保持程序运行。

I used this code: 我使用以下代码:

import socket

socket = socket.socket()
socket.bind(('127.0.0.1', 80))
socket.listen(1)
(con, address) = socket.accept()
while con.recv(1024) != b'exit':
    pass
else:
    con.close()
    socket.listen(1)
    (con, address) = socket.accept()

However, after the else clause the program runs further and the while statement will not run again and I do want the while statement to repeat itself. 但是,在else子句之后,程序会进一步运行,而while语句将不会再次运行,我确实希望while语句能够重复自身。 How can I achieve this? 我该如何实现?

simply make a containing loop... 只需创建一个包含循环...

import socket

while True:
    socket = socket.socket()
    socket.bind(('127.0.0.1', 80))
    socket.listen(1)
    (con, address) = socket.accept()
    while con.recv(1024) != b'exit':
        pass
    else:
        con.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM