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.App let;
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;
InputStreamRead er isr = null;
BufferedReader in = null;
PrintWriter out = null;
Button uptimeButton,wh oButton,dateBut ton;
TextArea ta;
public void init()
{
setBackground(C olor.white);
uptimeButton = new Button("uptime" );
uptimeButton.ad dActionListener (this); add(uptimeButto n);
whoButton = new Button("who"); whoButton.addAc tionListener(th is);
add(whoButton);
dateButton = new Button("date"); dateButton.addA ctionListener(t his);
add(dateButton) ;
ta = new TextArea("",20, 80);
ta.setEditable( false);
add(ta);
}
public void start()
{
try
{
s = new Socket(server,p ort);
isr = new InputStreamRead er(s.getInputSt ream());
in = new BufferedReader( isr);
out = new PrintWriter(s.g etOutputStream( ),true);
catch(Exception e)
{
ta.append("appl et error: "+e+"\n");
}
}
public void stop()
{
try
{
s.close();
}
catch(Exception e)
{
ta.append("appl et error: "+e+"\n");
}
}
public void actionPerformed (ActionEvent evt)
{
String query;
Object b = evt.getSource() ;
boolean newLine = true;
if (b==uptimeButto n) { query = "<query>upt ime</query>"; }
else if (b==whoButton) { query = "<query>who </query>"; }
else { query = "<query>dat e</query>"; }
try
{
out.println(que ry);
out.flush();
try
{
while ((c = in.read())!=-1)
{
ta.append(Strin g.valueOf((char ) c));
}
}
catch (IOException ioe)
{
ta.append("I/O error: "+ioe+"\n") ;
}
repaint();
}
catch(Exception e)
{
ta.append("appl et error: "+e+"\n");
}
}
}