fix server close
This commit is contained in:
parent
17a76e4b90
commit
1edf5226dc
24
server.py
24
server.py
@ -1,13 +1,18 @@
|
||||
import socket
|
||||
import threading
|
||||
import select
|
||||
|
||||
class Connection:
|
||||
sock=""
|
||||
addr=0
|
||||
|
||||
HOST = "127.0.0.1" # Standard loopback interface address (localhost)
|
||||
if 1:
|
||||
HOST = "0.0.0.0" # open to network
|
||||
else:
|
||||
HOST = "127.0.0.1" # Standard loopback interface address (localhost)
|
||||
PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
|
||||
clients=0
|
||||
run = True
|
||||
connections=[]
|
||||
|
||||
def send_message(conn, data):
|
||||
@ -17,7 +22,9 @@ def send_message(conn, data):
|
||||
|
||||
def handle_connection(conn):
|
||||
with conn.sock:
|
||||
while True:
|
||||
while run:
|
||||
ready_to_read, _, _ = select.select([conn.sock], [], [], 1.0)
|
||||
if ready_to_read:
|
||||
data = conn.sock.recv(1024)
|
||||
if data:
|
||||
send_message(conn, data)
|
||||
@ -26,15 +33,24 @@ def handle_connection(conn):
|
||||
connections.remove(conn)
|
||||
break
|
||||
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
|
||||
if __name__ == "__main__":
|
||||
hostname = socket.gethostname()
|
||||
IPAddr = socket.gethostbyname(hostname)
|
||||
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
try:
|
||||
s.bind((HOST, PORT))
|
||||
while True:
|
||||
print(f"Server {hostname} on ip {IPAddr}")
|
||||
while run:
|
||||
conn=Connection()
|
||||
s.listen()
|
||||
conn.sock, conn.addr = s.accept()
|
||||
connections.append(conn)
|
||||
threading.Thread(target=handle_connection, args=(conn,)).start()
|
||||
except KeyboardInterrupt:
|
||||
run = False
|
||||
print("Shutdown server")
|
||||
finally:
|
||||
s.close()
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user