how to make a URL conection through a seperate thread in the a client program


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Page 1 of 2 12 LastLast
Results 1 to 15 of 16

Thread: how to make a URL conection through a seperate thread in the a client program

Hybrid View

  1. #1
    Join Date
    Jul 2005
    Posts
    15

    Unhappy how to make a URL conection through a seperate thread in the a client program

    hi
    look into the program..... this is a client progrm... which will print on the screen all the characters sent from the server program..... but..... if a character '1' is received from the server it opens a thread inputthread1 and makes a URL connection to www.myportal.com. but i am getting 14 errors in the program..... will any kind heart can look into the bug and send a reply?
    thanks in advance

    here is the program
    import java.io.*;

    import java.net.*;

    public class MultimediaClient1 extends Thread

    {

    static Socket cs = null;
    static DataInputStream theTimestream;

    String theTime;

    public static void main(String args[])

    {

    try



    {

    cs=new Socket("localhost",4000);

    System.out.println("connected to server");
    BufferedReader in=new BufferedReader(new InputStreamReader(cs.getInputStream()));
    //InputThread1 st=new InputThread1(cs.getInputStream());
    //st.start();
    theTimestream=new DataInputStream(cs.getInputStream());
    String theTime=theTimestream.readLine();
    System.out.println(theTime);

    if (theTime=='1'){
    InputThread1 st=new InputThread1(cs.getInputStream());
    st.start();
    }

    InputScan is=new InputScan();



    is.start();



    while(true)



    {



    String msg;

    msg=in.readLine();

    System.out.println(msg);



    }



    }



    catch(Exception e){



    System.out.println(e);

    }



    }//end main



    }//end class





    class InputScan extends MultimediaClient1



    {



    DataInputStream stdin=new DataInputStream(System.in);



    public void run()



    {



    try



    {



    PrintWriter out=new PrintWriter(cs.getOutputStream(),true);



    while(true)



    {

    String msg;

    msg=stdin.readLine();

    out.println(msg);

    }



    }



    catch(Exception e)



    {



    System.out.println(e);



    }



    }



    }//end class

    class InputThread1 extends ServerSample1{
    Socket cs;
    InputStream is;
    public InputThread1(InputStream is){
    this.is=is;
    }
    public void run(){
    try{
    u=new URL("http://www.myportal.com");
    // now turn the URLinto a database stream
    try{
    uc=u.openConnection();
    DataInputStream theHTML =new DataInputStream(uc.getInputStream());
    try{
    while((thisLine=theHTML.readLine())!=null){
    System.out.println(thisLine);
    }
    }
    catch (Exception e){
    System.err.println(e);
    }
    }
    catch (Exception e){
    System.err.println(e);
    }
    }
    catch (MalformedURLException e){
    System.err.println(args[0]+"is not a parseable URL");
    System.err.println(e);
    }
    }
    }

  2. #2
    Join Date
    Aug 2003
    Posts
    313
    What are the errors that you are getting? I get the following:
    Code:
    Information: 10 errors
    Information: 3 warnings
    Information: Compilation completed with 10 errors and 3 warnings
    D:\Java_Projects\Test\src\MultimediaClient1.java
        Error:  line (120) cannot find symbol class ServerSample1
        Warning:  line (33) [deprecation] readLine() in java.io.DataInputStream has been deprecated
        Error:  line (36) operator == cannot be applied to java.lang.String,char
        Error:  line (38) cannot find symbol method start()
        Warning:  line (96) [deprecation] readLine() in java.io.DataInputStream has been deprecated
        Error:  line (130) cannot find symbol variable u
        Error:  line (133) cannot find symbol variable uc
        Error:  line (133) cannot find symbol variable u
        Error:  line (134) cannot find symbol variable uc
        Error:  line (136) cannot find symbol variable thisLine
        Warning:  line (136) [deprecation] readLine() in java.io.DataInputStream has been deprecated
        Error:  line (137) cannot find symbol variable thisLine
        Error:  line (149) cannot find symbol variable args
    But I think some of these are because your code doesn't include ServerSample1. I notice a lot of missing variable declarations and such as well.
    ~evlich

  3. #3
    Join Date
    Aug 2003
    Posts
    313
    These changes get rid of some of the errors:
    Code:
    import java.io.*;
    
    import java.net.*;
    
    public class MultimediaClient1 extends Thread {
    
        static Socket cs = null;
        static DataInputStream theTimestream;
    
        String theTime;
    
        public static void main(String args[]) {
            try {
                cs = new Socket("localhost", 4000);
    
                System.out.println("connected to server");
                BufferedReader in = new BufferedReader(new InputStreamReader(cs.getInputStream()));
    //InputThread1 st=new InputThread1(cs.getInputStream());
    //st.start();
                theTimestream = new DataInputStream(cs.getInputStream());
                String theTime = theTimestream.readLine();
                System.out.println(theTime);
    
                if (theTime.equals("1")) {
                    InputThread1 st = new InputThread1(cs.getInputStream());
                    st.start();
                }
    
                InputScan is = new InputScan();
                is.start();
                while (true) {
                    String msg;
                    msg = in.readLine();
                    System.out.println(msg);
                }
            }
            catch (Exception e) {
                System.out.println(e);
            }
        }//end main
    }//end class
    
    
    class InputScan extends MultimediaClient1 {
        DataInputStream stdin = new DataInputStream(System.in);
        public void run() {
            try {
                PrintWriter out = new PrintWriter(cs.getOutputStream(), true);
                while (true) {
                    String msg;
                    msg = stdin.readLine();
                    out.println(msg);
                }
            }
            catch (Exception e) {
               System.out.println(e);
            }
        }
    }//end class
    
    class InputThread1 extends ServerSample1 {
        Socket cs;
        InputStream is;
    
        public InputThread1(InputStream is) {
            this.is = is;
        }
    
        public void run() {
            try {
                URL u = new URL("http://www.myportal.com");
    // now turn the URLinto a database stream
                try {
                    BufferedReader theHTML = new BufferedReader(new InputStreamReader(u.openConnection().getInputStream()));
                    try {
                        String thisLine = null;
                        while ((thisLine = theHTML.readLine()) != null) {
                            System.out.println(thisLine);
                        }
                    }
                    catch (Exception e) {
                        e.printStackTrace(System.err);
                    }
                }
                catch (Exception e) {
                    e.printStackTrace(System.err);
                }
            }
            catch (MalformedURLException e) {
                System.err.println("http://www.myportal.com" + "is not a parseable URL");
                System.err.println(e);
            }
        }
    }
    Hope this helps.
    ~evlich

  4. #4
    Join Date
    Jul 2005
    Posts
    15
    Thanks a lot evlich........
    i tried the code in the alternate way ....it s same as your suggestion..... thanks .... but ... but why the line
    if (theTime.equals(the)){
    InputThread1 st=new InputThread1(cs.getInputStream());
    st.start();
    }
    is not working. I am not getting any syntax errors here.
    i want to start the thread if the string 'theTime " equals 'the' string only
    and i am not able to switch to the thread when the server sends the string "1".
    if i modify my code like bellow it is working and the program switches to the threas st.
    (theTime!=(the)){
    InputThread1 st=new InputThread1(cs.getInputStream());
    st.start();
    }

    and from my server i will send the string "1".


    help needed from kind brains.....

  5. #5
    Join Date
    Aug 2003
    Posts
    313
    When you compare references (any type of Object) in Java with the == or != operators, java is comparing to see whether the two objects are the same object, not whether they represent the same data. For instance, if you want to check to see if the input from the console is "DONE" then you need to do this:
    Code:
    String input = in.readLine();
    input.equals("DONE");
    If you use == here, you will always evaluate to false since the in.readLine() is constructing a String object and not using the one that was created at compile time. So when you say: "theTime!=(the)" that will probably always evaluate to false. Try
    "!theTime.equals(the)"

    Hope this helps.
    ~evlich

  6. #6
    Join Date
    Jul 2005
    Posts
    15
    Excellent evlich... excellent suggestion... thank you. The code works fine.
    but my purpose is not fully solved. i want InputThread1 st to start when theTime.equals(the) . it doesn't work when i say the following
    if ((theTime.equals(the))){
    InputThread1 st=new InputThread1(cs.getInputStream());
    st.start();
    }


    what is the modification ... kindly suggest . the complete code is as follows.
    (The program basically prints the input stream is from the server , now if the server sends the "1" string, the InputThread1 st should start .... but it doesnt work ....here is the full code


    import java.io.*;

    import java.net.*;

    public class MultimediaClient1 extends Thread

    {

    static Socket cs = null;
    static DataInputStream theTimestream;

    String theTime;

    public static void main(String args[])

    {

    try



    {

    cs=new Socket("localhost",4000);

    System.out.println("connected to server");
    BufferedReader in=new BufferedReader(new InputStreamReader(cs.getInputStream()));

    theTimestream=new DataInputStream(cs.getInputStream());
    String theTime=theTimestream.readLine();
    System.out.println(theTime);
    String the ="1";

    if ((theTime.equals(the))){ // THIS LINE IS PROBLEM EVLICH!!!!!
    InputThread1 st=new InputThread1(cs.getInputStream()); // THIS LINE IS PROBLEM EVLICH
    st.start();
    }

    InputScan is=new InputScan();



    is.start();



    while(true)



    {



    String msg;

    msg=in.readLine();

    System.out.println(msg);



    }



    }



    catch(Exception e){



    System.out.println(e);

    }



    }//end main



    }//end class





    class InputScan extends MultimediaClient1



    {



    DataInputStream stdin=new DataInputStream(System.in);



    public void run()



    {



    try



    {



    PrintWriter out=new PrintWriter(cs.getOutputStream(),true);



    while(true)



    {

    String msg;

    msg=stdin.readLine();

    out.println(msg);

    }



    }



    catch(Exception e)



    {



    System.out.println(e);



    }



    }



    }//end class

    class InputThread1 extends MultimediaClient1{
    Socket cs;
    InputStream is;
    public InputThread1(InputStream is){
    this.is=is;
    }
    public void run(){
    try{
    System.out.println("I am here Mr. Server");
    }
    catch (Exception e){

    System.err.println(e);
    }
    }
    }

  7. #7
    Join Date
    Jul 2005
    Posts
    15
    Thanks a lot evlich. The code given by you has clarified majority of my doubts. Thanks a lot....... agian.... and expecting the same co-operation in the future... good day...bye

  8. #8
    Join Date
    Jul 2005
    Posts
    15
    Also please ignore the post No 6 here, As it has being clarified by your mofified program...

  9. #9
    Join Date
    Jul 2005
    Posts
    15
    Dear evlich
    i am here again with a small error in the program which i could not solve for three hours.
    kindly glance a few lines of the server program for the client program given by you

    OutputThread ot=new OutputThread(cs.getOutputStream(),id1);
    ot.start();
    class OutputThread extends ServerSample1{
    PrintStream ps;
    DataInputStream is;
    InputThread it;
    int id1;

    public OutputThread(OutputStream os,int id1){ // idi is the identity of the client
    ps= new PrintStream(os);
    this.it=it;
    this.id1=id1;
    is=new DataInputStream(System.in);
    }

    public void run(){
    String line;
    try{
    /
    line=is.readLine();


    ((PrintWriter)v.elementAt(id1)).println(line);

    }
    catch (IOException e){
    System.err.println(e);
    }
    }
    }

    then i will type 1 in the server screen......
    kindly give some suggestions in the server program.... thanks a lot in advance

    srinivasan

  10. #10
    Join Date
    Jul 2005
    Posts
    15
    sorry i could not state the problem in the above thread.
    if i type 1 in the server screen ... the client must run the st thread right?. but it does not do so..
    Is it because the way i compare the strings in the client program is wrong?
    thanks

  11. #11
    Join Date
    Aug 2003
    Posts
    313
    What exactly is the error? This code looks decently fine. There is an odd '/' at the start of the try block and the v two lines after that doesn't seem to be declared. These are all errors that your compilier should give you. As far as logic goes, you are going to have to explain what exactly is going wrong with the program.
    ~evlich

  12. #12
    Join Date
    Aug 2003
    Posts
    313
    A few notes/modifications:
    1) Use BufferedReader instead of DataInputStream. e.g.
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    2) Compare strings using .equals(). e.g.
    "a".equals("b")

    I hope these help.

    PS. When posting code, it is preferable to pretty-print it in some way (indention and such, if it isn't too much trouble). Also, when you include code, please use the code tag ([\code] and [/\code], without the backslashes). Thanks.
    ~evlich

  13. #13
    Join Date
    Jul 2005
    Posts
    15
    Dera evlich
    i am extremly thankfull to you for your quick reply. Now i request you a few minutes of your valuable time to glance through the server program.
    let me first briefly explain the logic of the server program. The server send fixed messages to all its clients. when ever i type the string "1" in the server screen , the server program creates a thread called output thread ot and send that srting to the client( see above ). Now the client will compare the string with "1" , if true then creates a thread called InputThread1 st and makes a URL connection. The problem is the that even though the string"1" is typed in the server screen, the client is not able to run the st thread.
    i request to have a gance through the server program .i am posting the full server program however it is suffucient to glance only the outputThread ot .
    many many thaks again
    srinivasan

    here is the code of the server (and the cleint program is the same as you have given in this thread post No 3.) also there is obsolutely no syntax errors in both the programs.Only i am unab;e to resolve it logically.
    The server program
    import java.io.*;

    import java.net.*;

    import java.util.*;

    class ServerSample1 extends Thread





    {



    static ServerSocket ss;

    static Socket cs=null;

    static Vector v=new Vector(100);
    static Vector c=new Vector(100);
    static PrintWriter pw;

    static int id=0,id1=0;
    static int peak=0;
    static int temp=0;
    static int yes=0;
    static int no=0;

    int n,numb;

    public static void main(String args[]){
    try{
    ss=new ServerSocket(4000);
    System.out.println("Server has started");


    // to accept connections

    while(true){
    cs=ss.accept();
    new ServerThread(cs,id).start();
    InputThread it=new InputThread(cs,id1,cs.getInputStream(),cs.getPort(),temp,yes,no);
    it.start();
    OutputThread ot=new OutputThread(cs.getOutputStream(),id1);
    ot.start();
    System.out.println("Connected to the client,The ID given is "+id);
    pw=new PrintWriter(cs.getOutputStream(),true);

    v.addElement(pw);

    id++;
    id1++;
    }
    }
    catch(Exception e)



    {



    System.out.println(e);

    }

    }



    }//end class

    class ServerThread extends ServerSample1

    {

    Socket cs;

    int id;



    ServerThread(Socket ClientSocket,int id)



    {

    cs=ClientSocket;

    this.id=id;

    }



    public void run(){


    try{

    ((PrintWriter)v.elementAt(id)).print("WELCOME TO SERVER.");
    for(int i=0;i<v.size();i++)

    {


    ((PrintWriter)v.elementAt(i)).println(" The total clinets at precent are : "+v.size()+" The motion is proposed .Let us start the Voting process.The BALLOT is opened.please vote for a motion.Rules of voting: press y if you agree with the motion or press n if you wont agree with the motion.press any other key to defer the motion");
    }
    }
    catch(Exception e)

    {

    }



    }//end function run



    }//end class client server

    class InputThread extends ServerSample1{
    Socket cs;
    InputStream is;
    static Vector d=new Vector(100);
    static Vector d1=new Vector(100);
    static Vector d2=new Vector(100);
    int id1;
    int sa;
    int temp,yes,no;

    public InputThread(Socket ClientSocket,int id1,InputStream is,int sa,int temp,int yes,int no){
    cs=ClientSocket;
    this.is=is;
    this.id1=id1;
    this.sa=sa;
    this.temp=temp;
    this.yes=yes;
    this.no=no;
    int numb;

    }
    public void run(){
    try{

    int ia =is.read();
    Integer i = new Integer(is.read());


    char c=(char)ia;
    if(c=='y'){
    //yes++;
    d1.add(i);
    }
    else
    {if(c=='n')
    {//no++;
    d2.add(i);
    }
    else {System.out.println("Your vote is invalidated");}
    }

    System.out.println("The vote is recieved from"+id1+"and it is :"+c);
    System.out.println("The yes are:"+d1.size()+"And the No are:"+d2.size());
    if(d1.size()>d2.size()){
    System.out.println("The Motion is passed at this movement");
    ((PrintWriter)v.elementAt(id1)).println("The Motion is passed at this movement.");
    }
    else if(d1.size()<d2.size()){
    System.out.println("The motion is not passed at this movement");
    ((PrintWriter)v.elementAt(id1)).println("The Motion is not passed at this movement.");
    }
    else{ System.out.println("There is tie for the motion at this movement");
    ((PrintWriter)v.elementAt(id1)).println("The Motion is tie at this movement.");
    }

    ((PrintWriter)v.elementAt(id1)).println("There are some more votes to be polled,or waiting for the ballot to close");
    d.add(i);

    temp++;

    System.out.println("the No of votes polled: "+d.size());
    System.out.println("The Ballot box is >:"+d);


    }

    catch (IOException e){
    System.err.println(e);
    }
    }
    }


    class OutputThread extends ServerSample1{
    PrintStream ps;
    DataInputStream is;
    InputThread it;
    int id1;

    public OutputThread(OutputStream os,int id1){
    ps= new PrintStream(os);
    this.it=it;
    this.id1=id1;
    is=new DataInputStream(System.in);
    }

    public void run(){
    String line;
    try{
    //((PrintWriter)v.elementAt(id1)).println("1");
    line=is.readLine();

    //ps.println(line);
    ((PrintWriter)v.elementAt(id1)).println(line);

    }
    catch (IOException e){
    System.err.println(e);
    }
    }
    }

  14. #14
    Join Date
    Jul 2005
    Posts
    15
    I am posting the code again
    Code:
    import java.io.*;
    
    import java.net.*;
    
    import java.util.*;
    
    class ServerSample1 extends Thread
    
    
    
    
    
    {
    
    
    
     static ServerSocket ss;
    
     static Socket cs=null;
    
     static Vector v=new Vector(100);
     static Vector c=new Vector(100);
     static PrintWriter pw;
    
     static int id=0,id1=0;
     static int peak=0;
    static int temp=0;
    static int yes=0;
    static int no=0;
    
    int n,numb;
    
    public static void main(String args[]){
    try{
    ss=new ServerSocket(4000);
    System.out.println("Server has started");
    
    
    // to accept connections
    
    while(true){
    cs=ss.accept();
    new ServerThread(cs,id).start();
    InputThread it=new InputThread(cs,id1,cs.getInputStream(),cs.getPort(),temp,yes,no);
    it.start();
    OutputThread ot=new OutputThread(cs.getOutputStream(),id1);
    ot.start();
    System.out.println("Connected to the client,The ID given is "+id);
    pw=new PrintWriter(cs.getOutputStream(),true);
    
               v.addElement(pw);
    
    id++;
    id1++;
    }
    }
    catch(Exception e)
    
           
    
        {
    
           
    
             System.out.println(e);
    
        }
    
     }
    
     
    
    }//end class
    
    class ServerThread extends ServerSample1
    
    {
    
       Socket cs;
    
       int id; 
    
     
    
       ServerThread(Socket ClientSocket,int id)
    
     
    
        {
    
           cs=ClientSocket;
    
           this.id=id;
    
        }
    
    	
    
    public void run(){
    
    
    try{
    
    ((PrintWriter)v.elementAt(id)).print("WELCOME TO SERVER.");
    for(int i=0;i<v.size();i++)
    
                    {
    
    
    	((PrintWriter)v.elementAt(i)).println("  The total clinets at precent are :  "+v.size()+" The motion is proposed .Let us start the Voting process.The BALLOT is opened.please vote for a motion.Rules of voting: press y if you agree with the motion or press n if you wont agree with the motion.press any other key to defer the motion");
    }
    }
    catch(Exception e)
    
        {
    
        }
    
    
    
      }//end function run
    
    
    
    }//end class client server
    
    class InputThread extends ServerSample1{
    Socket cs;
    InputStream is;
    static Vector d=new Vector(100);
    static Vector d1=new Vector(100);
    static Vector d2=new Vector(100);
    int id1;
    int sa;
    int temp,yes,no;
    
    public InputThread(Socket ClientSocket,int id1,InputStream is,int sa,int temp,int yes,int no){
    cs=ClientSocket;
    this.is=is;
    this.id1=id1;
    this.sa=sa;
    this.temp=temp;
    this.yes=yes;
    this.no=no;
    int numb;
    
    }
    public  void run(){
    try{
    
    int ia =is.read();
    Integer i =  new Integer(is.read());
    	
    
    char c=(char)ia;
    if(c=='y'){
    	//yes++;
    	d1.add(i);
    	}
    	else
    	{if(c=='n')
    	{//no++;
    	d2.add(i);	
    		}
    	else {System.out.println("Your vote is invalidated");}
    			}
    
    System.out.println("The vote is recieved from"+id1+"and it is :"+c);
    System.out.println("The yes are:"+d1.size()+"And the No are:"+d2.size());
    if(d1.size()>d2.size()){
    	System.out.println("The Motion is passed at this movement");
    	((PrintWriter)v.elementAt(id1)).println("The Motion is passed at this movement.");
    	}
    else if(d1.size()<d2.size()){
    	System.out.println("The motion is not passed at this movement");
    	((PrintWriter)v.elementAt(id1)).println("The Motion is not passed at this movement.");
    	}
    else{	System.out.println("There is tie for the motion at this movement");
    	((PrintWriter)v.elementAt(id1)).println("The Motion is tie at this movement.");
    		}
    
    ((PrintWriter)v.elementAt(id1)).println("There are some more votes to be polled,or waiting for the ballot to close");
    d.add(i);
    
    temp++;
    
    System.out.println("the No of votes polled: "+d.size());
    System.out.println("The Ballot box is >:"+d);
    
    
    }
    
    catch (IOException e){
    System.err.println(e);
    }
    }
    }
    
    
    class OutputThread extends ServerSample1{
    PrintStream ps;
    DataInputStream is;
    InputThread it;
    int id1;
    
    public OutputThread(OutputStream os,int id1){
    ps= new PrintStream(os);
    this.it=it;
    this.id1=id1;
    BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
    //is=new DataInputStream(System.in);
    }
    
    public void run(){
    String line;
    try{
    //((PrintWriter)v.elementAt(id1)).println("1");
    line=is.readLine();
    
    //ps.println(line);
    ((PrintWriter)v.elementAt(id1)).println(line);
    
    }
     catch (IOException e){
    System.err.println(e);
    }
    }
    }

  15. #15
    Join Date
    Aug 2003
    Posts
    313
    Code:
    while (true) {
        cs = ss.accept();
        new ServerThread(cs, id).start();
        InputThread it = new InputThread(cs, id1, cs.getInputStream(), cs.getPort(), temp, yes, no);
        it.start();
        OutputThread ot = new OutputThread(cs.getOutputStream(), id1);
        ot.start();
        System.out.println("Connected to the client,The ID given is " + id);
        pw = new PrintWriter(cs.getOutputStream(), true);
    
        v.addElement(pw);
    
        id++;
        id1++;
    }
    So, from what I understand, this is the code that you are having problems with. When I run it, nothing happens because I'm not running a client as well.
    Some more comments:
    1) Is there a reason to use so many threads? I understand that if the program has a lot of clients then it would be necessary to handle things asyncronously, but for testing it would probably be best to remove them.
    2) Instead of subclassing Thread, you should probably just implement Runnable with some classes and then construct Threads around them.
    3) Your InputThread and OutputThread are using different protocols for transfering data. InputThread is expecting binary encoded data which OutputThread is writing as character encoded data.

    I'm attaching a small chat program that I wrote a long time ago. It is fairly simple and should work (hopefully I attached the correct version). Like I said, I wrote the program a long time ago before I really understood java. But if you take a look at the layout it might help.
    Attached Files Attached Files
    ~evlich

Similar Threads

  1. Replies: 60
    Last Post: 09-13-2002, 05:41 PM
  2. Replies: 0
    Last Post: 04-29-2002, 10:01 PM
  3. Replies: 0
    Last Post: 12-09-2001, 11:45 AM
  4. Java Thread
    By Kevin Chien in forum Java
    Replies: 3
    Last Post: 09-12-2000, 05:17 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center