Link to home
Start Free TrialLog in
Avatar of lll888
lll888

asked on

Socket programming sample

Hi All,

Since I am using jdk1.0.2, which does not have HttpUrlConnection class, I am using pure Socket class to retrieve files from a WWW server. However, my code just could not work properly. Here is what I do:

      DataInputStream ins;
      DataOutputStream outs;
      String response;

      try{
            Socket s = new Socket("www.yahoo.com",80);

            System.out.print("Connected.\n");
            ins = new DataInputStream(s.getInputStream());
            outs = new DataOutputStream(s.getOutputStream());

            String str = new String("GET /index.html HTTP/1.0 \n");
                  
            outs.writeBytes(str);
            outs.flush();
            outs.close();
            System.out.print("Send "+ str);

            System.out.print(ins.readLine());

            while ((response = ins.readLine())!= null)
                  {
                  System.out.print(response);
                  }

            System.out.print("\n\nDone.\n");
            }
      catch (Exception e)
            {
            System.out.print(e.toString());
            }


It seems that when I read from the socket, it returns nothing, and just blocks. Anyone knows how to solve this, or did I do something obviously wrong?

Thanks

Chengyan
Avatar of heyhey_
heyhey_

you must send several HTTP headers and one more blank line (CR LF) at the end of the request

typical request is

GET /index.html HTTP/1.0
User-Agent: Mozilla/4.0 (Windows NT 5.0;US) Opera 3.60  [en]
Accept: image/gif, image/x-xbitmap, image/jpeg, image/png, */*
Host: 127.0.0.1
<blank line>


get the HTTP spec from www.faqs.org (STD section)
ASKER CERTIFIED SOLUTION
Avatar of rainmal
rainmal

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Oops ...pls take out outs.close() from the outer try block

If you want to close the streams cause of an exception (which you should do) you should have another try..catch block preferebly after ins and outs are initalized.
 
typical example of such code is ,have a reference outside try {} catch{}

like

Socket s=null;
DataInputStream din=null;
DataOutputStream dout=null;

try
{
//initialize all of them here
}
catch(Exception ee)
{}
finally
{
  try
  {
     din.close();
     dout.close();
     s.close();
  }
  catch(Exception ignoreThis)
  {}
}

:(
Avatar of lll888

ASKER

Thanks for all the help, now it works.