Java timer and socket problem
I am trying to create a program that listens for a client input stream using socket programming and timer
but whenever the timer runs. he gets hanged
Please help me
here is the code ...
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
try
{
ServerUserName=jTextField1.getText();
ss=new ServerSocket(5000);
jButton1.enable(false);
jTextArea1.enable(true);
jTextField2.enable(true);
Timer t=new Timer(2000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
try
{
s=ss.accept();
InputStream is=s.getInputStream();
DataInputStream dis=new DataInputStream(is);
jTextArea1.append(dis.readUTF());
}
catch(IOException IOE)
{
}
catch(Exception ex)
{
setLbl(ex.getMessage());
}
}
});
t.start();
}
catch(IOException IOE)
{
}
}
Thanks in advance
+2
a source to share
3 answers
Each call accept
waits for a new client to connect to the server. The call is blocked until the connection is established. It looks like you have a single client that maintains a server connection.
One solution is pulling
s=ss.accept();
InputStream is=s.getInputStream();
DataInputStream dis=new DataInputStream(is);
outside the timer part of the code.
Update: keep in mind that readUTF
will still block if there is no data available to read.
+1
a source to share
I think you want to use socket timeouts instead of timer:
Thread listener = new Thread() {
ServerSocket ss;
@Override
public void run() {
try {
ss = new ServerSocket(5000);
ss.setSoTimeout(2000);
try {
while (true) {
try {
final String text = acceptText();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
jTextArea1.append(text);
}
});
} catch (final Exception ex) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setLbl(ex.getMessage());
}
});
}
}
} finally {
ss.close();
}
} catch (IOException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
private String acceptText() throws IOException {
Socket s = ss.accept();
try {
InputStream is=s.getInputStream();
try {
DataInputStream dis=new DataInputStream(is);
return dis.readUTF();
} finally {
is.close();
}
} finally {
s.close();
}
}
};
listener.setDaemon(true);
listener.start();
0
a source to share