特金特无法使用套接字...它展示了一个黑色的英亩



我创建了一个用于聊天的python程序,提供了有用的评论来理解该程序,但当我在pycharm中单击run时,它只是一个黑屏。。。

# Program that is a chatting app - NOT COMPLETED
from tkinter import *
import socket
# class msg to contain our program

class MsG:
# parameters self (automatic) and root which is main tkinter function
def __init__(self, root):
# host and port which details the information of the computer
self.host = 'host'
self.port = port
# socket initialization
self.s = socket.socket()
# binding socket to host and port
self.s.bind((self.host, self.port))
# allows maximum one connection to server
self.s.listen(1)
# accepts any connection 
self.c, self.addr = self.s.accept()
# creates a frame in the tkinter window with length 700 and width 1200
self.f = Frame(root, width=1200, height=700)
# attaches the frame to the screen
self.f.pack()
# creates a text space
self.t1 = Text(height=700, width=3)
# places it at x 1170 y 0
self.t1.place(x=1170, y=0)
# label to display that program is waiting for host
self.l1 = Label(font=('Arial', 16), text="Waiting for host...")
# placing label at x 0 y 0
self.l1.place(x=0, y=0)
# creating scrollbar oriented vertically so that it is convenient for server and host
self.sc = Scrollbar(root, orient=VERTICAL, command=self.t1.yview, width=30)
# binding it to t1
self.t1.configure(yscrollcommand=self.sc.set)
# attaching it to the right side
self.sc.pack(side=RIGHT, fill=Y)
# label to print client connected
self.l2 = Label(font="A client connected")
# if condition so that if client accepts connection l1 is removed from the program
if self.s.accept():
self.l1.place_forget()
self.l2.place(x=0, y=5)

# main tkinter window
root = Tk()
# creating object mb of class MsG with parameter root so that everything can happen in the tkinter window
mb = MsG(root)
# handles any events
root.mainloop()

我应该为这个程序的套接字部分创建一个不同的类,还是其他什么?

socket.accept是一个阻塞调用。您需要避免在GUI上下文中进行这些调用,因为事件循环停止运行。通常为这些任务创建不同的线程,但其他解决方案也是可能的。我还建议使用选择器,因为它不仅更容易,还为代码增加了安全性。

作为的一个例子

相关内容

最新更新