如何使用tkinter停止作为套接字线程一部分的while循环?

时间:2018-04-06 11:31:29

标签: python multithreading sockets tkinter

下面写的代码将用户连接到另一个用户。问题是当客户端用户退出应用程序时,由于在第57行开始的while循环,带有日期信息的空字符串仍然在服务器用户的屏幕上打印。所以我的问题是,如何在客户端用户关闭应用程序后停止接收空字符串消息? 谢谢。

server.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import time
from datetime import datetime
import socket
import threading
try:
    import Tkinter as tk
except ImportError:
    import tkinter as tk


root = tk.Tk()
root.title("Server")

text = tk.Text(master=root)
text.pack(expand=True, fill="both")

entry = tk.Entry(master=root)
entry.pack(expand=True, fill="x")

frame = tk.Frame(master=root)
frame.pack()


def buttons():
    for i in "Connect", "Send", "Clear", "Exit":
        b = tk.Button(master=frame, text=i)
        b.pack(side="left")
        yield b


b1, b2, b3, b4 = buttons()


class Server:
    def __init__(self):
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.__c = None

    @property
    def c(self):
        return self.__c

    @c.setter
    def c(self, c):
        self.__c = c

    @c.deleter
    def c(self):
        del self.__c

    def connect(self):
        self.s.bind(("", 12345))
        self.s.listen(10)
        now = str(datetime.now())[:-7]
        text.insert("insert", "Date: {}\nConnected.\n".format(now))
        c, addr = self.s.accept()
        text.insert("insert", "Date: {}\n{} connected.\n".format(str(datetime.now())[:-7], addr))
        self.__c = c
        while True:
            data = str(self.__c.recv(1024))[1:]
            now = str(datetime.now())[:-7]
            text.insert("insert", "\nDate: {}\nClient: {}\n".format(now, data))
            time.sleep(2)

    def send(self):
        respond = str(entry.get())
        self.__c.sendall(bytes(respond.encode("utf-8")))
        now = str(datetime.now())[:-7]
        entry.delete("0", "end")
        text.insert("insert", "\nDate: {}\nServer: {}\n".format(now, respond))


s1 = Server()


def connect():
    t1 = threading.Thread(target=s1.connect)
    t1.start()


def send():
    t2 = threading.Thread(target=s1.send)
    t2.start()


def destroy():
    root.destroy()


def clear():
    text.delete("1.0", "end")


b1.configure(command=connect)
b2.configure(command=send)
b3.configure(command=clear)
b4.configure(command=destroy)

t0 = threading.Thread(target=root.mainloop)
t0.run()

client.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import time
from datetime import datetime
import socket
import threading
try:
    import Tkinter as tk
except ImportError:
    import tkinter as tk


root = tk.Tk()
root.title("Client")

text = tk.Text(master=root)
text.pack(expand=True, fill="both")

entry = tk.Entry(master=root)
entry.pack(expand=True, fill="x")

frame = tk.Frame(master=root)
frame.pack()


def buttons():
    for i in "Connect", "Send", "Clear", "Exit":
        b = tk.Button(master=frame, text=i)
        b.pack(side="left")
        yield b


b1, b2, b3, b4 = buttons()


class Client:
    def __init__(self):
        self.__s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    @property
    def s(self):
        return self.__s

    @s.deleter
    def s(self):
        del self.__s

    @s.setter
    def s(self, s):
        self.__s = s

    def connect(self):
        self.__s.connect(("", 12345))
        now = str(datetime.now())[:-7]
        text.insert("insert", "Tarih: {}\nSunucuya bağlandı.\n".format(now))
        while True:
            data = str(self.__s.recv(1024))[1:]
            now = str(datetime.now())[:-7]
            text.insert("insert", "\nTarih: {}\nİstemci: {}\n".format(now, data))
            time.sleep(2)

    def send(self):
        respond = str(entry.get())
        now = str(datetime.now())[:-7]
        self.__s.sendall(bytes(respond.encode("utf-8")))
        entry.delete("0", "end")
        text.insert("insert", "\nTarih: {}\nİstemci: {}\n".format(now, respond))


c1 = Client()


def connect():
    t1 = threading.Thread(target=c1.connect)
    t1.start()


def send():
    t2 = threading.Thread(target=c1.send)
    t2.start()


def destroy():
    root.destroy()


def clear():
    text.delete("1.0", "end")


b1.configure(command=connect)
b2.configure(command=send)
b3.configure(command=clear)
b4.configure(command=destroy)

t0 = threading.Thread(target=root.mainloop)
t0.run()

1 个答案:

答案 0 :(得分:0)

解决以下代码。

<强> server.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import time
from datetime import datetime
import socket
import threading
try:
    import Tkinter as tk
except ImportError:
    import tkinter as tk


root = tk.Tk()
root.title("Server")

text = tk.Text(master=root)
text.pack(expand=True, fill="both")

entry = tk.Entry(master=root)
entry.pack(expand=True, fill="x")

frame = tk.Frame(master=root)
frame.pack()


def buttons():
    for i in "Connect", "Send", "Clear", "Disconnect", "Exit":
        b = tk.Button(master=frame, text=i)
        b.pack(side="left")
        yield b


b1, b2, b3, b4, b5 = buttons()


class Server:
    def __init__(self):
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.__c = None

    @property
    def c(self):
        return self.__c

    @c.setter
    def c(self, c):
        self.__c = c

    @c.deleter
    def c(self):
        del self.__c

    def connect(self):
        self.s.bind(("", 12345))
        self.s.listen(10)
        now = str(datetime.now())[:-7]
        text.insert("insert", "Date: {}\nConnected.\n".format(now))
        c, addr = self.s.accept()
        text.insert("insert", "Date: {}\n{} connected.\n".format(str(datetime.now())[:-7], addr))
        self.__c = c
        self.condition()

    def condition(self):
        while self.__c is not None:
            data = str(self.__c.recv(1024))[1:]
            now = str(datetime.now())[:-7]
            text.insert("insert", "\nDate: {}\nClient: {}\n".format(now, data))
            time.sleep(2)

    def send(self):
        respond = str(entry.get())
        self.__c.sendall(bytes(respond.encode("utf-8")))
        now = str(datetime.now())[:-7]
        entry.delete("0", "end")
        text.insert("insert", "\nDate: {}\nServer: {}\n".format(now, respond))


s1 = Server()


def connect():
    t1 = threading.Thread(target=s1.connect)
    t1.start()


def send():
    t2 = threading.Thread(target=s1.send)
    t2.start()


def disconnect():
    s1.c = None


def destroy():
    root.destroy()


def clear():
    text.delete("1.0", "end")


b1.configure(command=connect)
b2.configure(command=send)
b3.configure(command=clear)
b4.configure(command=disconnect)
b5.configure(command=destroy)

t0 = threading.Thread(target=root.mainloop)
t0.run()

<强> client.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import time
from datetime import datetime
import socket
import threading
try:
    import Tkinter as tk
except ImportError:
    import tkinter as tk


root = tk.Tk()
root.title("Client")

text = tk.Text(master=root)
text.pack(expand=True, fill="both")

entry = tk.Entry(master=root)
entry.pack(expand=True, fill="x")

frame = tk.Frame(master=root)
frame.pack()


def buttons():
    for i in "Connect", "Send", "Clear", "Disconnect", "Exit":
        b = tk.Button(master=frame, text=i)
        b.pack(side="left")
        yield b


b1, b2, b3, b4, b5 = buttons()


class Client:
    def __init__(self):
        self.__s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    @property
    def s(self):
        return self.__s

    @s.deleter
    def s(self):
        del self.__s

    @s.setter
    def s(self, s):
        self.__s = s

    def connect(self):
        self.__s.connect(("", 12345))
        now = str(datetime.now())[:-7]
        text.insert("insert", "Date: {}\nConnected.\n".format(now))
        self.condition()

    def condition(self):
        while self.__s is not None:
            data = str(self.__s.recv(1024))[1:]
            now = str(datetime.now())[:-7]
            text.insert("insert", "\nDate: {}\Server: {}\n".format(now, data))
            time.sleep(2)

    def send(self):
        respond = str(entry.get())
        now = str(datetime.now())[:-7]
        self.__s.sendall(bytes(respond.encode("utf-8")))
        entry.delete("0", "end")
        text.insert("insert", "\nDate: {}\nClient: {}\n".format(now, respond))


c1 = Client()


def connect():
    t1 = threading.Thread(target=c1.connect)
    t1.start()


def send():
    t2 = threading.Thread(target=c1.send)
    t2.start()


def clear():
    text.delete("1.0", "end")


def destroy():
    root.destroy()


def disconnect():
    c1.s = None


b1.configure(command=connect)
b2.configure(command=send)
b3.configure(command=clear)
b4.configure(command=disconnect)
b5.configure(command=destroy)
t0 = threading.Thread(target=root.mainloop)
t0.run()