简体   繁体   English

如何使套接字服务器Python永远运行

[英]How to make socket server Python run forever

I have this code create a simple socket server Python.But it closes down each time client disconnect, how to I make it run forever? 我用这段代码创建了一个简单的套接字服务器Python,但是每次客户端断开连接时它都会关闭,如何使其永久运行?

import socket

HOST = ''
PORT = 8000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)

conn, addr = s.accept()
with conn:
        print('Connected by', addr)
        while True:
            data = conn.recv(1024)
            print(data)
            conn.sendall('HelloClient'.encode())
            if not data:
                continue

If you want run forever just add a while True loop and accept the connections inside the loop. 如果要永久运行,只需添加while True循环并接受循环内的连接即可。

See here for an example. 请参阅此处的示例。

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

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