Python-当我单击“连接”时,我的程序不断关闭/不响应/重新启动

时间:2018-08-06 13:06:21

标签: python sockets tkinter restart

这意味着它是一个程序,可通过tkinter窗口轻松地通过套接字发送消息,该窗口位于python2中。每当我尝试连接时,窗口冻结几秒钟,然后关闭并离开外壳。我不知道它可能是bind()或connect()。我认为可能是具有永久循环的线程使一切崩溃。

import socket
from Tkinter import *
import threading
import time
import msvcrt
import pickle
from threading import Thread
from urllib2 import urlopen
import re
def restart():
    try:
        public_ip = urlopen('http://ip.42.pl/raw').read()
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        local_ip=(s.getsockname()[0])
        s.close()
    except:
        pass
    quality=1

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    master = Tk()
    master.minsize(300,100)
    master.geometry("500x500")
    master.title("Chat")
    session=True
    session_file = open('receive.cht', 'w')
    pickle.dump(session, session_file)
    session_file.close()
    session_file = open('send.cht', 'w')
    pickle.dump(session, session_file)
    session_file.close()



    def editor(display_box, var):
        while True:
            try:
                display_box_checkbutton_value=str(var.get())
                if display_box_checkbutton_value=='1':
                    display_box.configure(state=NORMAL)
                if display_box_checkbutton_value=='0':
                    display_box.configure(state=DISABLED)
            except:
                pass
    def receive(master, host_entry, port_entry, display_box, var):    
        try:

            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            host=str(host_entry.get())
            port=int(port_entry.get())
            binding=True
            while binding==True:
                try:
                    sock.bind((host, port))
                    binding=False
                except:
                    port=port+1
            while True:
                data , addr=sock.recvfrom(1024)
                received_message=('\n'+data.decode('UTF-8')+" received from: "+str(addr))
                display_box.insert(END,received_message)

        finally:
            sock.close()

    def send(master, host_entry, port_entry, message_entry, display_box,var):
        try:

            host=str(host_entry.get())
            port=int(port_entry.get())
            message=message_entry.get()
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            def sendmessage(message, host, port):
                    sock.sendto((message).encode('UTF-8'), (host,port))
                    sent_message=('\n'+"Me: "+ message)
                    display_box.insert(END,sent_message)
                    master.after(500)
            sendmessage(message, host, port)
        finally:
            sock.close()




    def connect( master, host_entry, port_entry, sock, message_label, message_entry, send_button, display_box, tr):            
        try:
            host=host_entry.get()
            port=int(port_entry.get())
            session_file = open('receive.cht', 'r')
            session= pickle.load(session_file)
            if session==True:
                sock.connect((host,port))
                session=False
                session_file = open('receive.cht', 'w')
                pickle.dump(session, session_file)
                session_file.close()

            title=("Connected to: "+ host, ":"+str(port))
            connection_archieved_label=Label(master, text=title)
            display_text='Online, say hi.'
            display_box.delete(1.0,END)
            display_box.insert(END,display_text)
            connection_archieved_label.place(x=300,y=0)
            message_label.configure(state=NORMAL)
            message_entry.configure(state=NORMAL)
            send_button.configure(state=NORMAL)
            receive_thread = threading.Thread(target=receive, args=[master, host_entry, port_entry, display_box, var])
            receive_thread.start()
            editor_checkbutton_thread = threading.Thread(target=editor, args=[display_box, var])
            editor_checkbutton_thread.start()
            sock.close()
            if tr==1:
                tr=2
                connect( master, host_entry, port_entry, sock, message_label, message_entry, send_button, display_box, tr)

        except Exception,e:
            global connection_failed_label
            connection_failed_label.configure(background="red", state=NORMAL)
            connection_failed_label.place(x=140, y=85)




    var=StringVar()
    enable_display_box_checkbutton = Checkbutton(master, text="Color image", variable=var,onvalue=True, offvalue=False)
    enable_display_box_checkbutton=Checkbutton(master, text="Chat View", variable=var)
    enable_display_box_checkbutton.select()
    enable_display_box_checkbutton.place(x=340, y=55)

    display_box =Text(master)
    display_box.configure(state='disabled')
    display_box.place(x=50,y=80,height=240,width=410)

    connection_failed_label=Label(master, text=("Connection failed: Check the port and host"))
    connection_failed_label.place(x=46, y=78)
    connection_failed_label.place_forget()



    message_label=Label(master, text="Message",  state=DISABLED)
    message_label.place(x=220,y=337)
    message_entry = Entry(master, state=DISABLED)
    message_entry.place(x=125,y=360,height=21,width=250)
    send_button = Button(master, text="Send", state=DISABLED,  command=lambda:send(master, host_entry, port_entry, message_entry, display_box,var))#send
    send_button.place(x=375,y=360, height=21,width=40)

    host_label=Label(master, text="Host")
    host_label.place(x=170,y=0)
    host_entry = Entry(master)
    host_entry.place(x=200,y=0,height=23,width=150)
    port_label=Label(master, text="Port")
    port_label.place(x=170,y=25)
    port_entry = Entry(master)
    port_entry.place(x=200,y=25,height=23,width=150)
    tr=1
    connect_button = Button(master, text="Connect",  command=lambda:connect(master, host_entry, port_entry, sock, message_label, message_entry, send_button, display_box, tr))  #connect
    connect_button.place(x=240,y=50)



    my_ips_label=Label(master, text="Your Ip's:")
    my_ips_label.place(x=400,y=0)

    public_ip_label=Label(master, text=public_ip)
    public_ip_label.place(x=395,y=15)

    local_ip_label=Label(master, text=local_ip)
    local_ip_label.place(x=395,y=30)


    try:
        fil  = open('contacts.txt', 'r')
        contact_entry=True
    except:
        contact_entry=False

    contact_choose = StringVar(master)
    contact_choose.set("Contacts")

    if contact_entry==True:
        with open('contacts.txt','r') as f:
            next(f)
            next(f)
            wordlist =[line.split(None, 1)[0] for line in f]
        name_of_contact=wordlist
    try:
        contact_choice = OptionMenu(master, contact_choose, *name_of_contact)
        contact_choice.place(x=200, y=400)
    except:
        pass
    def load(master, contact_choose, host_entry, port_entry):
        contact=contact_choose.get()+' '
        fil=open('contacts.txt', 'r')
        for line in fil:
            if re.match(contact, line):
                lines=str(line)
        ip=lines.split()[1]
        port=lines.split()[2]
        host_entry.delete(0, END)
        host_entry.insert(END, ip)
        port_entry.delete(0, END)
        port_entry.insert(END, port)
    try:
        load_button=Button(master, text="Load", command=lambda:load(master, contact_choose, host_entry, port_entry))
        load_button.place(x=290,y=402,  height=27,width=35)
    except:
        pass
    def new_contact(master):
        def add(master, name_of_contact_entry, ip_of_contact_entry, port_of_contact_entry, new_contact_master):        
            try:
                fil  = open('contacts.txt', 'r')            
                fil  = open('contacts.txt', 'a')
                print"no"
                name=(name_of_contact_entry.get())
                ip=(ip_of_contact_entry.get())
                port=(port_of_contact_entry.get())
                info='\n'+name+' '+ip+' '+port
                fil.write(info)
                new_contact_master.configure(background='green')
                master.after(500)
                new_contact_master.destroy()
            except:
                try:
                    fil  = open('contacts.txt', 'w')
                    name=(name_of_contact_entry.get())
                    ip=(ip_of_contact_entry.get())
                    port=(port_of_contact_entry.get())
                    info="contact list:"+ '\n'+" __name ip port__ "+'\n'+name+' '+ip+' '+port
                    fil.write(info)
                    new_contact_master.configure(background='green')
                    master.after(500)
                    new_contact_master.destroy()
                except:
                    pass

        new_contact_master = Tk()
        new_contact_master.geometry("300x150")
        new_contact_master.title("New Contact")

        name_of_contact_label=Label(new_contact_master, text="Name:")
        name_of_contact_label.place(x=57,y=7)
        name_of_contact_entry=Entry(new_contact_master)
        name_of_contact_entry.place(x=100,y=10)
        ip_of_contact_label=Label(new_contact_master, text="Ip:")
        ip_of_contact_label.place(x=78,y=30)
        ip_of_contact_entry=Entry(new_contact_master)
        ip_of_contact_entry.place(x=100,y=33)
        port_of_contact_label=Label(new_contact_master, text="Port:")
        port_of_contact_label.place(x=66,y=53)
        port_of_contact_entry=Entry(new_contact_master)
        port_of_contact_entry.place(x=100,y=56)
        add_button=Button(new_contact_master, text='Add', command=lambda:add(master,name_of_contact_entry, ip_of_contact_entry, port_of_contact_entry, new_contact_master)).place(x=100,y=80, height=21,width=125)
    new_contact_button=Button(master, text='New Contact', command=lambda:new_contact(master)).place(x=120,y=402,  height=27,width=80)
    mainloop()
restart()

0 个答案:

没有答案