0

I have created a python program for chatting, helpful comments have been provided to understand the program, however when I click run in pycharm, it's just a black screen...

# 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()

should I create a different class for the socket part of this program, or something else?

1 Answers1

0

socket.accept is a blocking call. You need to avoid these calls in a GUI context, since the eventloop stops running. Usually one creates a different thread for those tasks but other solutions are possible as well. I also would recommend to use selector, cause its not just easier, it adds security to your code.

As an example

Thingamabobs
  • 7,274
  • 5
  • 21
  • 54