vendredi 17 juin 2016

I tried to build a simple messenger but the message pops up only when the other user presses Return. How to modify that?

I built a simple messenger using socket and Tkinter modules. But there seems to be one problem. The message from the other user displays only when the first one presses the Return key to send his message. I tried enough to fix this but I can't.

Here are my codes (Sorry for too much code, but had to include all that):

Server.py

from Tkinter import *
import socket

host = '127.0.0.1'
port = 5000

s = socket.socket ()
s.bind ((host, port))

s.listen (1)
c, addr = s.accept ()

root = Tk ()
topFrame = Frame (root)
topFrame.pack ()
bottomFrame = Frame (root)
bottomFrame.pack (side = BOTTOM)

scrollBar = Scrollbar (topFrame)
scrollBar.pack (side = RIGHT, fill = Y)

textArea = Listbox (topFrame, width = 40, height = 10, yscrollcommand = scrollBar.set)
textArea.pack (side = LEFT)
scrollBar.config (command = textArea.yview)

enterText = Entry (bottomFrame, width = 30)

textArea.insert (0, "Connection with client established")

def sendText (event):
    global c, textArea, enterText
    text = enterText.get ()
    c.send (text)
    textArea.insert (0, "SERVER: " + enterText.get ())
    enterText.delete (0, END)
    root.update ()
    data = c.recv (1024)
    textArea.insert (0, "CLIENT: " + str (data))
    root.update ()

enterText.pack (side = LEFT, padx = 10, pady = 5)
enterText.bind ('<Return>', sendText)

Send = Button (bottomFrame, text = "Send")
Send.pack (side = RIGHT, padx = 10, pady = 5)

mainloop ()
c.close ()`

Client.py

from Tkinter import *
import socket

host = '127.0.0.1'
port = 5002

s = socket.socket ()
s.connect ((host, port))

root = Tk ()

topFrame = Frame (root)
topFrame.pack ()
bottomFrame = Frame (root)
bottomFrame.pack (side = BOTTOM)

scrollBar = Scrollbar (topFrame)
scrollBar.pack (side = RIGHT, fill = Y)

textArea = Listbox (topFrame, width = 40, height = 10, yscrollcommand = scrollBar.set)
textArea.pack (side = LEFT)
scrollBar.config (command = textArea.yview)

enterText = Entry (bottomFrame, width = 30)

textArea.insert (0, "Connection with server established")

def sendText (event):
    global s, textArea, enterText
    text = enterText.get ()
    s.send (text)
    textArea.insert (0, "CLIENT: " + enterText.get ())
    enterText.delete (0, END)
    root.update ()
    data = s.recv (1024)
    textArea.insert (0, "SERVER: " + str (data))
    root.update ()


enterText.pack (side = LEFT, padx = 10, pady = 5)
enterText.bind ('<Return>', sendText)

Send = Button (bottomFrame, text = "Send")
Send.pack (side = RIGHT, padx = 10, pady = 5)

mainloop ()
s.close ()

P.S. - I am just a beginner and trying to learn

Aucun commentaire:

Enregistrer un commentaire