Hi I'm doing a project for school and wrote an applet that makes a socket
connection to a server (smae host as webserver) that was setup for this
project. In the applet there are 3 buttons and by pressing one of them it
triggers a specific query, like getting the server uptime, date or who (is
online). The problem is that when I press one of the buttons it send the
query to the server, reads from the BufferedReader. This goes all well but
then it 'hangs'. I think the problem is in the line:
while ((c = in.read())!=-1)
If I replace the while by a single read() then it works just fine, except
that I need to output the whole BufferedReader not just 1 char. The docs
specify that when the method read() reaches the end of the buffer it
returns -1. But it seems that c never gets to be -1. I've been googling for
several hours now and according to the docs on java.sun.com it whould be
working. What's wrong here?
Thanks for help!
Jonathan
--------------------------
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class test extends Applet implements ActionListener
{
private static int port = 2000;
private static String server = "xxxxxxxxx";
int c;
Socket s;
InputStreamReader isr = null;
BufferedReader in = null;
PrintWriter out = null;
Button uptimeButton,whoButton,dateButton;
TextArea ta;
public void init()
{
setBackground(Color.white);
uptimeButton = new Button("uptime");
uptimeButton.addActionListener(this); add(uptimeButton);
whoButton = new Button("who"); whoButton.addActionListener(this);
add(whoButton);
dateButton = new Button("date"); dateButton.addActionListener(this);
add(dateButton);
ta = new TextArea("",20,80);
ta.setEditable(false);
add(ta);
}
public void start()
{
try
{
s = new Socket(server,port);
isr = new InputStreamReader(s.getInputStream());
in = new BufferedReader(isr);
out = new PrintWriter(s.getOutputStream(),true);
catch(Exception e)
{
ta.append("applet error: "+e+"\n");
}
}
public void stop()
{
try
{
s.close();
}
catch(Exception e)
{
ta.append("applet error: "+e+"\n");
}
}
public void actionPerformed(ActionEvent evt)
{
String query;
Object b = evt.getSource();
boolean newLine = true;
if (b==uptimeButton) { query = "<query>uptime</query>"; }
else if (b==whoButton) { query = "<query>who</query>"; }
else { query = "<query>date</query>"; }
try
{
out.println(query);
out.flush();
try
{
while ((c = in.read())!=-1)
{
ta.append(String.valueOf((char) c));
}
}
catch (IOException ioe)
{
ta.append("I/O error: "+ioe+"\n");
}
repaint();
}
catch(Exception e)
{
ta.append("applet error: "+e+"\n");
}
}
}