I’m writing a simple IRC server and client GUI using wxPython. In my application, I had two threads running: One for the GUI, and one for the socket connections required to send and receive information. So far, I believe that I am successfully connecting to the server with the client application, but I am seeing no messages processed. I tried using my client with another TCP listener application and I was able to send a message successfully. I believe the problem lies in the way I have set up the GUI. Here is my code for the serverside application (apologies for any awkward spacing)
I have a feeling the problem lies within the bootUp() function..
#!/usr/bin/python
import wx
import socket
import threading
from threading import Thread
ip = ""
port = 0
backlog = 5
chatText = ""
class relayServerGUI(wx.Frame):
def __init__(self, parent, id):
wx.Frame.__init__(self, parent, id, "Enter IP address", size = (600, 600))
orciPanel = wx.Panel(self)
relayChat = wx.TextCtrl(orciPanel, 0, chatText, (50, 50), (500, 500),style = wx.TE_MULTILINE)
portInput = wx.TextEntryDialog(None, "Enter Port: ", "")
if portInput.ShowModal() == wx.ID_OK:
global port
port = int(portInput.GetValue())
thread2()
def relayInterpretor():
socketRelay = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socketRelay.bind((ip, port))
socketRelay.listen(backlog)
client, address = socketRelay.accept()
while 1:
relayData = client.recv(1024)
global chatText
chatText += (relayData)
client.send(relayData)
def bootUP():
if __name__ == "__main__":
relayApplication = wx.PySimpleApp()
relayFrame = relayServerGUI(parent = None, id = -1)
relayFrame.Show()
relayApplication.MainLoop()
while 1:
relayChat.Clear()
relayChat.AppendText(chatText)
Thread(target = bootUP).start()
def thread2():
Thread(target = relayInterpretor).start()
EDIT: relayChat is where the messages would, ideally, be displayed. I set it to copy chatText, a global string variable so I would not have to delve into cross-threading.
I am not very fluent in wx, but I think this problem isn’t very specifically wx related anyways. I see two possible issues here.
First, you are sharing a string between threads to communicate text to the
relayChatwidget, which is usually a very bad approach. There should be a way for your to emit an event in wx from the thread, so that the event loop will pick it up in the main thread and run a handler that updates the widget.Secondly, the event loop…
That is a blocking call. Your application enters the event loop, so this following code is not getting executed:
Again, this ties back into the first point. When the socket in the thread receives some data, it should be emitting an event with that data, so the main gui thread can properly call a handler that will append to your widget.
Update
Referencing this question on how to emit custom wx events, you could probably fix it like this:
*Note: I am not 100% on that syntax. Try it out. It may need a slight tweak.