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