Reputation: 25
I am making a Java Socket Swing Application. I created this void:
private static void sendMessage(JTextField message) {
try {
String data = user + ": " + message.getText();
out.println(data);
System.out.println(in.readLine());
}
catch(Exception exc) {
JOptionPane.showMessageDialog(dpanel,
"Could not send message. Reason: " + exc, "",
JOptionPane.ERROR_MESSAGE);
}
}
The program gets jammed up after I try to send the second message to the server. Can someone provide any recommendations for my code? Thanks!
P.S.
sendMessage()
is triggered by a MouseLisitener
for a JButton
.
There is a PipeStream
for System.err
and out to a JTextArea
.
This is what in out and connection is/are:
try {
connection = new Socket(ipa, port);
out = new PrintWriter(connection.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(connection.getInputStream())));
}
...
Upvotes: 0
Views: 196
Reputation: 25
I deleted void part and put it in the mouse listener and open and closed the connection every time I sent a message. That prevented the program crashing. Thanks for helping me realize my errors.
Upvotes: 0
Reputation: 347204
It sounds like you are trying to call potentially blocking I/O from within the context of the Event Dispatching Thread. This is NEVER a good idea, anything that will block the EDT will stop (amongst other things) repaint requests and stop the EDT from processing mouse and keyboard events...
All interaction with the UI (creation and modification) should be done from within the context of the EDT.
I would suggest you take a look at Concurrency in Swing for some background...
In your case, you are going to need some kind of Thread
or background worker that is capable of sending and receiving data via your socket. This would allow you to queue out going messages and process the results without blocking the EDT.
But how this is actually implemented will come down to exactly what you requirements are...
Upvotes: 3
Reputation: 285403
Issues:
Upvotes: 3