Passively listening on a socket for a chat application
-
27-06-2021 - |
题
I am currently developing a chat application which is quite basic overall, however I am encountering problems when receiving strings from both the client and the server side. I am using a thread to passively listen on the socket for incoming messages, which is where I suspect the problem to be. Am I doing this the right way?
Source: Code for sending strings:
send.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
messageBuffer = message.getText();
out.println(messageBuffer);
chat.append(username + ": " + messageBuffer + "\n");
message.setText("");
}
});
I then have this which passively listens (problem is probably here):
public void run(){
while(true){
try {
messageBufferIn = in.readLine();
System.out.println(in.readLine());
chat.append(recipient + ": " + messageBufferIn + "\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Im also calling the thread using this:
public static void startChatting(){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thanks for any help you can provide, Im still new to threads overall so my mistake might be quite mediocre.
Edit: The problem is when I try sending a message to the receiver, nothing comes through, I can confirm that they are connected. In fact the System.out.println(in.readLine()); doesnt come through at all, not even a "null" output.
解决方案
you have got issue with Concurency in Swing, Swing GUI don't know that you running / open the
Socket
onBackground Task
,all updates to the
Swing GUI
must be done on EDT, otherwise nothing happened or you got a few exceptionshave to wrap all updates from
Background Task
(in your caseRunnable#Thread
) to theinvokeLater
for Swing GUIwhile(true){
is endless loop put thereBoolean variable
instead oftrue
, then you can to stop, start or restart whatever in your caseSocket
in the case that
send.addActionListener(new ActionListener(){
runs only once time (if user invoked byJButtons
click) then to use SwingWoker for opening Socket,SwingWorker
quite good guarantee that all output should be done on EDTdifference betweens
Runnable#Thread
andSwingWorker
is thatSwingWorker
is designated to run only once times
其他提示
I suspect your main problem is that you're not flushing the OutputStream
. You'll want to add out.flush()
after you've finished writing to it and want to send the message. For example, your ActionListener
would look like this:
send.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
messageBuffer = message.getText();
out.println(messageBuffer);
out.flush();
chat.append(username + ": " + messageBuffer + "\n");
message.setText("");
}
});
If you don't do this, your OutputStream
will sit there until it's buffer's full (which will be a lot of messages).