當我斷開服務器中的所有客戶端時,服務器不會繼續運行。我該怎么做活服務器
import socket, threading, tkinter
服務器
import socket, threading, tkinter
import time
def sendDisconnectAll(my_clients):
for client in my_clients:
conn = client[0]
conn.sendall('Disconnect'.encode('utf8'))
conn.close()
def handle_client(conn, addr):
while True:
try:
request_from_clients = conn.recv(1024).decode('utf8') #sample request
print(request_from_clients)
if request_from_clients == 'SignIn':
conn.sendall('Accept Sign in'.encode('utf8'))
except:
print('Client has been shutdown')
break
my_clients = []
def live_server():
global thr
global s
while True:
try:
conn, addr = s.accept()
my_clients.append((conn, addr))
thr = threading.Thread(target=handle_client, args=(conn, addr))
thr.daemon = True
thr.start()
except:
print("Error")
HOST = '127.0.0.1'
PORT = 8000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen()
print('HOST: ', HOST)
print('PORT: ', PORT)
thr = threading.Thread(target=live_server)
thr.daemon = True
thr.start()
count_time = time.time()
while True:
now = time.time()
if (int(now - count_time) 1) % 10 == 0: #Disconnect all clients after 10 seconds
count_time = now
request = 'Disconnect'
print('Disconnect all')
sendDisconnectAll(my_clients)
客戶
import socket, threading
import tkinter as tk
from tkinter import *
def signIn():
global client
request = 'SignIn'
try:
client.sendall(request.encode('utf8'))
client.recv(1024).decode('utf8')
except:
print('Server has been shutdown')
IP = input("Enter IP: ")
PORT = input("Enter PORT: ")
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
client.connect((IP, int(PORT)))
except:
print("Can't connect to server")
client.close()
def live_client():
global client
while True:
print(client.recv(1024).decode('utf8'))
thr = threading.Thread(target=live_client)
thr.daemon = True
thr.start()
app = Tk()
app.title('CLIENT')
but_connect = tk.Button(app, text="SIGN IN",
width=20, command=signIn)
but_connect.pack(pady=6)
app.mainloop()
謝謝!
uj5u.com熱心網友回復:
問題是您只將客戶添加到my_clients串列中。讓我們看看在服務器中發生了什么:
- 服務器啟動
- 它接收一個客戶并將其添加到
my_clients - 在下一次斷開所有操作時,該客戶端的套接字已關閉,但該客戶端仍保留在串列中
- 在以下斷開所有操作時,服務器的主執行緒嘗試寫入關閉的套接字并引發例外
- 由于所有其他執行緒都是守護執行緒,因此應用程式結束。
my_clients關閉所有客戶端套接字后,您必須清除串列:
def sendDisconnectAll(my_clients):
for client in my_clients:
conn = client[0]
conn.sendall('Disconnect'.encode('utf8'))
conn.close()
my_clients.clear()
當心:我沒有看客戶端代碼......
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/387700.html
上一篇:客戶端只在發送訊息時監聽服務器
下一篇:檢查多列并從其他多列回傳到單元格
