| View previous topic :: View next topic |
| Author |
Message |
zengrz Cheater
Reputation: 0
Joined: 19 Mar 2009 Posts: 33 Location: ca
|
Posted: Sun May 15, 2011 4:48 am Post subject: Java - single-threaded network socket problem |
|
|
Hi.
I am writing a basic Java network chat program. My problem is that when I use readLine() from the InputStreamReader class to listen for a message, the method blocks the program until a message is received. It creates a problem as I need my program to be updated constantly, regardless of if a message is received. While I have found a way around by creating another thread for the sole purpose of receiving data, I remember that the winsock in VB does similar things by generating events (DataArrival, ConnectionEstablished) to deal with new messages without blocking the program. Is there a way to generate an event whenever a message is received in Java?
Another problem: when I terminate the either the client or the server prematurely (while they are listening for an incoming message using readLine()), Java generates an error. Is there a way to properly handle the situation without raising an exception?
Thank you very much!
Last edited by zengrz on Sun May 15, 2011 5:44 pm; edited 1 time in total |
|
| Back to top |
|
 |
HomerSexual Grandmaster Cheater Supreme
Reputation: 5
Joined: 03 Feb 2007 Posts: 1657
|
|
| Back to top |
|
 |
Innovation Grandmaster Cheater
Reputation: 12
Joined: 14 Aug 2008 Posts: 617
|
Posted: Sun May 15, 2011 9:24 am Post subject: |
|
|
You could encapsulate the receiving of data in a class that extends Thread, create a new instance of the class, and call its start method. Have the thread call a method/callback of the main instance when there's a new message.
| Code: | public class MessageReceptor extends Thread
{
private Chat chat;
public MessageReceptor(Chat chat)
{
this.chat = chat;
}
public void run()
{
...
String message;
...
chat.receiveMessage(message)
...
}
} |
| Code: | public class Chat
{
public startReceivingMessages()
{
new MessageReceptor(this).start();
}
public receiveMessage(String message) {...}
} |
As for the exception, catch IOException or InterruptedIOException.
Last edited by Innovation on Fri May 27, 2011 7:12 pm; edited 1 time in total |
|
| Back to top |
|
 |
zengrz Cheater
Reputation: 0
Joined: 19 Mar 2009 Posts: 33 Location: ca
|
Posted: Sun May 15, 2011 9:47 pm Post subject: |
|
|
thanks guys for the quick response!
thanks HomerSexual for the code, i'll keep it as a reference. I realize that your friend may be using the technique I was looking for, I will definitely look into that.
Innovation, I think I kinda done the same thing you have done, but thanks for the code example. Also, I did catch the exceptions, but they just kept showing up for some reason. Sometime later I will test the program out and see if the error really matters, well..
Thanks all!
|
|
| Back to top |
|
 |
|