Solved

client/server question

Posted on 2003-11-23
28
629 Views
Last Modified: 2010-03-31
Hi, below are two files, c(the client) and serverz(the server). When I press the rock button in c the client makes a connection to serverz, serverz then servers out a string to the client but the client doesnt seem to get the string from the server. Is display.append the correct method?, display.appendText throws an error. Im loading the client from a webpage.
Cheers

This is the code

/**************************webpage code (c.html)**********************************/
<html>
<applet code="c.class" width=300 height=225>
</applet>
</html>

/*************************************c.java*************************************/

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.lang.*;

// Client class to let a user

public class c extends Applet
                             implements Runnable {
   
         //TextArea display;
      
      public c(){
      //super("c");
      TextArea display;
            display = new TextArea(20 , 10);
            add("Center" , display);
            resize(300 , 150);
            show();
      }
      
   private JTextField id;
   private JTextArea display;
   private JPanel boardPanel, panel2;
   //private Socket connection;
   //private DataInputStream input;
   private DataOutputStream output;
   private Thread outputThread;
   private char myMark;
   private boolean myTurn;
            Socket client;
            InputStream input;
      //Socket client;
      //InputStream input;
      //OutputStream output1;
     
     
     
     private Button pushButton1, pushButton2, pushButton3;
     public void init(){
           pushButton1 = new Button("\nRock");
                 pushButton2 = new Button("\nSissors");
                       pushButton3 = new Button("\nPaper");
                       
     add(pushButton1);  
          add(pushButton2);  
               add(pushButton3);
               
   
               }
               
        public boolean action( Event e, Object o, Graphics g){
              while(true){
              //check to see if a button triggered an event
              if(e.target instanceof Button){
                    if(e.target == pushButton1){
                          try{
                                g.drawString("\nText from server is\n\t");
                          //receiving message from server      
                  client = new Socket(InetAddress.getLocalHost(),5003);
                  input = client.getInputStream();
                  display.append("\nCreated input Stream\n");
                  display.append("\nText from server is\n\t");
                  char c;
                  
                  while((c = (char) input.read() ) != '\n')
                        display.append(String.valueOf( c ));
            
                  display.append("\n");
                  client.close();
                  
                  //sending message to server
            Socket connection  = null;
            OutputStream output = connection.getOutputStream();
            String s = new String("Has connected\n");
            
            for(int i = 0; i < s.length(); ++i)
                  output.write((int) s.charAt(i));
                    
                          }
                          catch ( IOException io){
                                io.printStackTrace();
                          }//end catch
              
                    }//end try
                    
     
        }
              return true;
                 }//end while
    }
   // Make connection to server and get associated streams.
   // Start separate thread to allow this applet to
   // continually update its output in text area display.
 

   // Control thread that allows continuous update of the
   // text area display.
   public void run()
   {

   }
         
 
   

}

/**********************************serverz.java*********************************************/

import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import javax.swing.*;

public class serverz extends Frame{
     TextArea display;

     public serverz(){
          super("serverz");
          display = new TextArea(20 , 5);
          add("Center" , display);
          resize(300 , 150);
          show();
     }

     public void runserverz(){

     ServerSocket serve = null;
     Socket connection;
     OutputStream output = null;

     BufferedReader input = null;

     try{
          //sending message to client
          serve = new ServerSocket(5003 , 1000);
          connection = serve.accept();
          display.setText("\nConnection received");
          output = connection.getOutputStream();
          String s = new String("Has connected\n");

          for(int i = 0; i < s.length(); ++i)
               output.write((int) s.charAt(i));

          display.appendText(
               "\nSent message");

          //receiving message from client
          input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
          String buffer = null;
          while((buffer = input.readLine()) != null) {
            display.appendText("\n" + buffer);
          }


     }

     catch(IOException e){
          e.printStackTrace();
     }
     // Always close
     finally {
       try {
         output.close();
         input.close();
         serve.close();
       }
       catch(IOException e) {
         e.printStackTrace();
       }
     }
}
     public boolean handleEvent( Event e )
{
     if( e.id == Event.WINDOW_DESTROY ){
          hide();
          dispose();
          System.exit( 0 );
     }

     return super.handleEvent( e );
}

public static void main(String args[]){
     serverz s = new serverz();
     s.runserverz();
}
}






























0
Comment
Question by:eire_ireland
  • 14
  • 8
  • 6
28 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 9807227
Please close your previous question, which I've already answered, before we go on to this one.
0
 
LVL 92

Expert Comment

by:objects
ID: 9807238
> while((c = (char) input.read() ) != '\n')

One problem is you read until you recieve a newline, but your server does not appear to send one.
0
 
LVL 92

Expert Comment

by:objects
ID: 9807244
Use of a Reader/Writer would make reading/writing string easier.
0
 
LVL 92

Expert Comment

by:objects
ID: 9807252
> Please close your previous question, which I've already answered

Which apparently doesn't work :)
0
 

Author Comment

by:eire_ireland
ID: 9807304
I have closed the other question, what question did u answer objects?
0
 
LVL 92

Expert Comment

by:objects
ID: 9807312
something like:

client:

input = client.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(input));
display.append("\nCreated input Stream\n");
display.append("\nText from server is\n\t");
String fromServer = in.readLine();
Display.append(fromServer);
in.close();


server:

output = connection.getOutputStream();
PrintWriter out = new PrintWriter(output);
String s = new String("Has connected\n");
out.println(s);
out.close();
0
 
LVL 92

Expert Comment

by:objects
ID: 9807318
> what question did u answer objects?

this one :)
0
 

Author Comment

by:eire_ireland
ID: 9807340
Did you compile that code?, cos its not working for me, im using j2sdk1.4.3_02. Are you sure its not something to do with the display method?
0
 
LVL 92

Expert Comment

by:objects
ID: 9807385
> Did you compile that code?,

No,  and it may have minor errors in it. Was just intended as a guide.

> Are you sure its not something to do with the display method?

what display method?

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9807401
eire-ireland - this site is buggy as usual - i have not been receiving email updates.

>>
Which apparently doesn't work :)
>>

What do you mean by that and where did you get that idea?
0
 

Author Comment

by:eire_ireland
ID: 9807450
It was objects that said something didnt work, your code works fine for me. I havent used e e for a while, why was it changed, it worked perfectly before, the screens were much more readable.
Below is some client code, Im trying to implement a button but it throws the following error:

--------------------Configuration: j2sdk1.4.0_02 <Default>--------------------
C:\Program Files\Xinox Software\JCreator Pro\MyProjects\clientz.java:30: variable ev might not have been initialized
            if(ev.target == a)
                   ^
Note: C:\Program Files\Xinox Software\JCreator Pro\MyProjects\clientz.java uses or overrides a deprecated API.
Note: Recompile with -deprecation for details.
1 error

Process completed.

/******************************clientz.java************************/

import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.lang.*;

public class clientz extends Frame {
     TextArea display;
     private Button a;

     public clientz(){
          super("clientz");
          a = new Button("Rock");
          display = new TextArea(20 , 10);
          add("Center" , display);
          resize(300 , 150);
          show();
     }

     public void runClient(){
           Event ev;
           Object o;
          Socket client = null;
          InputStream input = null;
          //input.read();
          PrintWriter output = null;

          try{
            if(ev.target == a)  //this is line 30
            {
               //receiving message from server
               client = new Socket(InetAddress.getLocalHost(),5003);
               input = client.getInputStream();
               display.appendText("\nCreated input Stream\n");
               display.appendText("\nText from server is\n\t");
               char c;

               while((c = (char) input.read() ) != '\n')
                    display.appendText(String.valueOf( c ));

               display.appendText("\n");
              }

 
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9807480
>>It was objects that said something didnt work, your code works fine for me.

No - that's OK - i was addressing objects.

If you're using a gui, you need to add an ActionListener to any button

button.addActionListener(this); // the main class implements ActionListener

Then you should run client/server code on a new thread in the handler though.

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9807500
>>if(ev.target == a)  //this is line 30

The proper code would then be, in the event handler (actionPerformed)

if(ev.getSource() == a)
0
 
LVL 92

Expert Comment

by:objects
ID: 9807555
>  Im trying to implement a button but it throws the following error:

I'm confused now, you q states the comms between the client and server is not working. But now you are stating that it doesn't compile.
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 92

Expert Comment

by:objects
ID: 9807566
And the class you posted that doesn't compile is not even mentioned in the original q??
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9807567
You seem to have started talking about a completely different bit of code

was: c.java
is now: clientz.java
0
 
LVL 92

Expert Comment

by:objects
ID: 9807592
And a different problem
0
 

Author Comment

by:eire_ireland
ID: 9807718
I could'nt get c..java working so I went I  started working off clientz.java, I suppose I should posted it as a new question, i just didnt think to, isnt it the same thing anyway since the original problem isnt working?
0
 
LVL 92

Expert Comment

by:objects
ID: 9807736
> isnt it the same thing anyway since the original problem isnt working?

No the original problem is caused by a logic problem, while the second is a syntax error.
See my earlier comments for fixing the posted question.


0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9807753
It might be an idea to ask CS (http://www.experts-exchange.com/Community_Support/) to delete this question and give you your points back, then repost the question.
0
 

Author Comment

by:eire_ireland
ID: 9807755
objects, your sample code didnt work for me
0
 

Author Comment

by:eire_ireland
ID: 9807764
Ill just post this question here. I want to use buttons to send one of three different strings to the server depending on the button pressed. below is the client code i am using. Its your code CEHJ.

import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.lang.*;

public class clientz extends Frame {
     TextArea display;
     private Button a;

     public clientz(){
                    super("clientz");
           a = new Button("Rock");
           add("North" , a);
 
          display = new TextArea(20 , 10);
          add("Center" , display);
          resize(300 , 150);
          show();
     }
     
   

     public void runClient(){
          Socket client = null;
          InputStream input = null;
          //input.read();
          PrintWriter output = null;

          try{

               //receiving message from server
               client = new Socket(InetAddress.getLocalHost(),5003);
               input = client.getInputStream();
               display.appendText("\nCreated input Stream\n");
               display.appendText("\nText from server is\n\t");
               char c;

               while((c = (char) input.read() ) != '\n')
                    display.appendText(String.valueOf( c ));

               display.appendText("\n");

               //sending message to server
               output = new PrintWriter(new OutputStreamWriter(client.getOutputStream()), true);
               String message = "Client to Server!";
               output.println(message);

          }
          catch(IOException e) {
               e.printStackTrace();
          }
          finally {
            try {
              input.close();
              output.close();
              client.close();
            }
            catch(IOException e) {
              e.printStackTrace();
            }
          }
     }

          public boolean handleEvent( Event e )
{
     if( e.id == Event.WINDOW_DESTROY ){
          hide();
          dispose();
          System.exit( 0 );
     }

     return super.handleEvent( e );
}

public static void main( String args[]){
         clientz c = new clientz();
     c.runClient();
 


}
}
0
 
LVL 92

Expert Comment

by:objects
ID: 9807777
> Ill just post this question here.

So you no longer want to fix the original problem?
0
 

Author Comment

by:eire_ireland
ID: 9807781
Well its still the same problem, the original problem was my attempt to fix it.
0
 
LVL 92

Accepted Solution

by:
objects earned 50 total points
ID: 9807782
use the following code and just add new buttons as required:

import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.lang.*;

public class clientz extends Frame {
     TextArea display;
     private Button a;

     public clientz(){
                   super("clientz");
          a = new Button("Rock");
          a.addActionListener(new ActionListener()
             { public void actionPerformed(ActionEvent event) { runClient("Rock"); }});
          add("North" , a);
 
          display = new TextArea(20 , 10);
          add("Center" , display);
          resize(300 , 150);
          show();
     }
     
   

     public void runClient(String message){
          Socket client = null;
          InputStream input = null;
          //input.read();
          PrintWriter output = null;

          try{

               //receiving message from server
               client = new Socket(InetAddress.getLocalHost(),5003);
               input = client.getInputStream();
               display.appendText("\nCreated input Stream\n");
               display.appendText("\nText from server is\n\t");
               char c;

               while((c = (char) input.read() ) != '\n')
                    display.appendText(String.valueOf( c ));

               display.appendText("\n");

               //sending message to server
               output = new PrintWriter(new OutputStreamWriter(client.getOutputStream()), true);
               output.println(message);

          }
          catch(IOException e) {
               e.printStackTrace();
          }
          finally {
            try {
              input.close();
              output.close();
              client.close();
            }
            catch(IOException e) {
              e.printStackTrace();
            }
          }
     }

          public boolean handleEvent( Event e )
{
     if( e.id == Event.WINDOW_DESTROY ){
          hide();
          dispose();
          System.exit( 0 );
     }

     return super.handleEvent( e );
}

public static void main( String args[]){
        clientz c = new clientz();
     //c.runClient();
 


}
}
0
 
LVL 92

Expert Comment

by:objects
ID: 9807784
> Well its still the same problem, the original problem was my attempt to fix it.

No they are different problems.
0
 

Author Comment

by:eire_ireland
ID: 9807806
ok, i wanted to use buttons to send a string back to the server so it appears that i have two problems wraped up in one, I phrase questions more clearly.

anyway, thanks for the help... that works for me
0
 
LVL 92

Expert Comment

by:objects
ID: 9807816
No worries :-)

http://www.objects.com.au
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now