Newbie
Newbie

Reputation: 200

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?

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

Upvotes: 2

Views: 3765

Answers (1)

attdona
attdona

Reputation: 18983

If you want run forever just add a while True loop and accept the connections inside the loop.

See here for an example.

Upvotes: 4

Related Questions