Solved

client/server question (beginner level)

Posted on 2003-11-22
7
298 Views
Last Modified: 2010-03-31
Hi, below are two simple files. clientz is a client and serverz is the server.
I can read strings from the server but I want the server to also be able to read strings from the client (on the same port, in this program port no 5003). How to I go about this?. this is really wrecking my head, i just cant figure it out. Any help or suggestions to code/design would be great, thanks.

/*************************************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;
      
      public clientz(){
            super("clientz");
            display = new TextArea(20 , 10);
            add("Center" , display);
            resize(300 , 150);
            show();
      }
      
      public void runClient(){
            Socket client;
            InputStream input;
            //input.read();
            
            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");
                  client.close();
                  
                  //sending message to server
      
            }
            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();

}
}
/***********************************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;
      Socket connection;
      OutputStream output;
      
      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
      
      }
      
      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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
7 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 9803813
You just need to get and use the output stream on the client and input stream on the server respectively. Don't forget to close them after use.
0
 

Author Comment

by:eire_ireland
ID: 9803831
Could you give me an example of this plz, pseudocode will do cos I was tryin something like that and it would'nt work... again thanks
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9803843
Show what you had and we'll try to correct it
0
MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

 

Author Comment

by:eire_ireland
ID: 9803923
           //sending message to server
            Socket connection;
            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));

            OutputStream output = connection.getOutputStream();
                                      ^
--------------------Configuration: j2sdk1.4.0_02 <Default>--------------------
C:\Program Files\Xinox Software\JCreator Pro\MyProjects\clientz.java:41: variable connection might not have been initialized
            OutputStream output = connection.getOutputStream();
                                      ^
Process completed.
/**************************************************************/

Thats the error its giving.

If I initialize the connection again without specifying a different port number it throws an error specifying the port number is already in use.
Any ideas?



                  
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 50 total points
ID: 9804197
You can do this sort of thing:

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;

     public clientz(){
          super("clientz");
          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();

}
}


//-------------------------------


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
 

Author Comment

by:eire_ireland
ID: 9807228
Thats greay, thanks a mil
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9807389
:-)
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
jdbc error in jsp application 20 89
Java string replace 11 77
Glassfish admin console not working 1 88
Using jdbcTemplate.batchUpdate to improve INSERT performance 6 32
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses

734 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