Trying to write a UDP client-server application using Swing. Each instance of the client should be able to send messages to the Server (from the event dispatch thread) and also continuously listen for messages from other clients relayed through the server (on a worker thread using SwingWorker). I'm trying to implement a ListenWorker class now whose doInBackground method will continuously listen for UDP datagrams, and publish the data to the process() method, with will update a JTextArea on the client JFrame with the message. However, I'm running into some difficulties due to my inexperience with SwingWorker and general Swing concurrency. Here is the gist of the code I wrote so far:
public class ListenWorker extends SwingWorker<void, String> {
public ListenWorker(int port, JTextArea textArea){
// set up socket
}
protected void doInBackground(){
while(true){
// code to receive Datagram
publish(messageFromDatagram);
}
}
protected void process(List<String> messages){
for(String message : messages){
textArea.append(message);
}
}
}
However, my IDE is giving me an error in the first line where I start the class defintion, saying "illegal start of type" due to void being there. As far as I can see, I want my doInBackground to be a void method, since I intend it to run indefinitely, listening for datagrams from the various clients. Java doesn't seem to want to let me have it as a void method though. How would I code a way around this?
You probably want java.lang.Void
to represent the doInBackground()
return type; for example SwingWorker<Void, String>
.
Addendum: doInBackground()
would then return null
.