Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 17 of 17

Thread: Help with a client server program

  1. #1
    Junior Member
    Join Date
    Aug 2014
    Posts
    29
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Help with a client server program

    Hi all,
    I am trying to create a java client server application, that eventually will turn into an android client application. For now i am still trying to understand the technology behind it b4 getting into the android stuff.

    Initially i used plain java socket programming, mainly because i knew that better than anything else. But i came to the conclusion that i can not use it, because (and correct me if i am wrong) i want to ask from the server various things at various times. From what i know on socket programming, i have to follow a specific patern, server is expecting something and replies to that while the client is expecting exactly what the server is going to transmit.

    I would like to have the freedom to ask anything from the server at any time. for example, i might need a list of cities at first and then a list of shops, where on a second client i might need to get the complete shop list first with out the cities. (this is just a simple example i just thought).

    I have been looking around servlet for the last couple of days, and it seems that tomcat should do that job, using the get commands, but i am kinda lost. On one of the tutorials i found, the server had different functions returning different things, String/Html/Xml, but acceptin all different types of parameters.
     @GET
      @Produces(MediaType.TEXT_PLAIN)
      public String sayPlainTextHello() {
        return "Hello Jersey";
      }
     
      // This method is called if XML is request
      @GET
      @Produces(MediaType.TEXT_XML)
      public String sayXMLHello() {
        return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";
      }
     
      // This method is called if HTML is request
      @GET
      @Produces(MediaType.TEXT_HTML)
      public String sayHtmlHello() {
        return "<html> " + "<title>" + "Hello Jersey" + "</title>"
            + "<body><h1>" + "Hello Jersey" + "</body></h1>" + "</html> ";
      }
    and when connecting with the server it was asking for a specific parameter.(if i got that right as well)
     // Get plain text
        System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_PLAIN).get(String.class));
        // Get XML
        System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_XML).get(String.class));
        // The HTML
        System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_HTML).get(String.class));

    Any way, its a long post, so my question is, can i use some client server technology that i can call specific functions or variables from the server to be sent dynamically to the client?

    Thanks for any information provided,
    ilias


  2. #2
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    666
    Thanks
    0
    Thanked 121 Times in 105 Posts

    Default Re: Help with a client server program

    Quote Originally Posted by skarosg3 View Post
    (and correct me if i am wrong) i want to ask from the server various things at various times. From what i know on socket programming, i have to follow a specific patern, server is expecting something and replies to that while the client is expecting exactly what the server is going to transmit.
    You are wrong.
    You can send anything at any point in time. There are no artificial limitations.
    The network will simply send a stream of bytes from one point to the other within the network. What you do with these bytes, how you interprete them, etc, is completely up to you.

  3. #3
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with a client server program

    From what i know on socket programming, i have to follow a specific patern, server is expecting something and replies to that while the client is expecting exactly what the server is going to transmit.
    That sounds like a description of a protocol like http. With your own server you can define your own protocol.
    If you don't understand my answer, don't ignore it, ask a question.

  4. #4
    Junior Member
    Join Date
    Aug 2014
    Posts
    29
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Help with a client server program

    Quote Originally Posted by Cornix View Post
    You are wrong.
    You can send anything at any point in time. There are no artificial limitations.
    The network will simply send a stream of bytes from one point to the other within the network. What you do with these bytes, how you interprete them, etc, is completely up to you.
    I might be able to work around to it then, keep the socket open and sent streams of text representing the operation i need, then the server can execute the apropriate functions (after checking the incoming string on some if/case statement).

    Quote Originally Posted by Norm View Post
    That sounds like a description of a protocol like http. With your own server you can define your own protocol.
    From what i have read the last 2 days, i think that this is more appropriate, but can i call from a java/android client specific functions or just the get method?

  5. #5
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    666
    Thanks
    0
    Thanked 121 Times in 105 Posts

    Default Re: Help with a client server program

    Are you actually talking about Sockets or about a HTML server?
    Sockets do not have a "get" method. Sockets have input and output streams.

  6. #6
    Junior Member
    Join Date
    Aug 2014
    Posts
    29
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Help with a client server program

    Ok, lets take things from the begining.
    I need to create a client server application for android.
    I CREATED a socket server that worked ok for a rough demo version of what i want to do.
    As things got bigger i realised that a serialised input output architecture(as i was using initialy on my socket server) wouldnt do the job.
    Plus, i had/have a problem making my java application (raw java classes) run on tomcat, or some other kind of server. So by looking at my possibilities of how to resolve these, i got lost

    I have a basic socket server (that doesnt work as it is to an online server) so i am in a cross road i guess, i could keep the socket server, change it in such a way to make it work no matter what the client sents to it (i was thinking as i said before, an infinite loop where the server will check for the clients request and acts accordingly) and if that works to find a way to make it a WAR file (something that Eclipse doesnt allow me to do) in order to publish it on line,
    OR, I could create an html server using tomcat/apache that is easier to publish online but dont know how to use.

    My initial question was can i use html server to ask from the server any kind of information, or i have to use the technic i mention on my first post?

    If i stick to my java project with sockets, how can i change that in order to publish it online?(tried Ant but only got a jar file, can not create a WAR that seems to be the kind i need in order to publish)

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with a client server program

    can i use html server to ask from the server any kind of information,
    I think that is possible.

    I'm not sure what a WAR file is for. Do server hosting sites require that?

    Your testing server code sounds like it needs a redesign. The accept logic should start a thread to service the incoming request and pass it the connection that it just received and loop back to wait for the next connection.
    If you don't understand my answer, don't ignore it, ask a question.

  8. #8
    Junior Member
    Join Date
    Aug 2014
    Posts
    29
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Help with a client server program

    Quote Originally Posted by Norm View Post
    I'm not sure what a WAR file is for. Do server hosting sites require that?
    WAR is Web Archive, and from what i have read online, is what tomcat needs to run. I am not sure about it, but i think jar will not work with it. WAR files are supposed to have some extra stuff that jar dont.

    Why do you say that my server needs redesign? Here is (some part of) my code

    public static void main(String[] args)
        {
        	UserInterfaceThread inter = new UserInterfaceThread();
            inter.start();
            bank =inter.getBanks();
        	Server server = new Server();
            server.start();  
        }
     public void run() {
            try {
                serverSocket = new ServerSocket(port);  //Server socket
            } catch (IOException e) {
                System.out.println("Could not listen on port: "+port);
            }
     
            System.out.println("Server started. Listening to the port "+port);
            while (true) { 
                    try {
                    DataInputStream in =new DataInputStream(server.getInputStream());
                	 DataOutputStream out = new DataOutputStream(server.getOutputStream());
                	 //waiting for incoming requests
                	 String inMess=in.readUTF();
                     if(request is A){
                           //Do something here
                     }
                     else if (request is B){
                           //Do something different
                     }
                  } //try
             catch (IOException ex) {
                    System.out.println("Problem in message reading");
                }
        }//while
        }

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with a client server program

    Where is the accept() method to wait for incoming connections?
    If you don't understand my answer, don't ignore it, ask a question.

  10. The Following User Says Thank You to Norm For This Useful Post:

    skarosg3 (August 28th, 2014)

  11. #10
    Junior Member
    Join Date
    Aug 2014
    Posts
    29
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Help with a client server program

    I forgot about that. Its been working fine till now, but i have been working with only one client, so there was no problem there. I will have to read a bit about it to remember how it works. If i have an issue i will post back, thanks.

    how is the rest looking? it should do the job, right?

    I have an issue keeping the socket open from the android client, rather than reopening a new one, but thats an other subject, let alone i havent looked it up at all yet.

    When i have a more complete code, could i post it to have a look here?

    thanks, ilias

  12. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with a client server program

    how is the rest looking? it should do the job, right?
    I don't see how the posted code works without using an accept().
    Here's a idea of how it could work:
    server defines serversocket
    begin loop
    server calls accept() and waits for connect
    client connects
    server creates a new object giving it the socket from accept() and puts the new object on a thread
    end loop

    The new object handles the client's communications
    If you don't understand my answer, don't ignore it, ask a question.

  13. #12
    Member jdv's Avatar
    Join Date
    Jul 2014
    Location
    This Land
    Posts
    73
    Thanks
    0
    Thanked 5 Times in 5 Posts

    Default Re: Help with a client server program

    My advice is to look at Java WebSockets for this sort of thing.

  14. #13
    Junior Member
    Join Date
    Aug 2014
    Posts
    29
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Help with a client server program

    @Norm
    How does this look 2 u?
    The main Server class
    public class Server extends Thread {
        public static ArrayList<Branch> bank;
     public static void main(String[] args)
        {
    UserInterfaceThread inter = new UserInterfaceThread();
            inter.start();
            bank =inter.getBanks();
    try {
            	ServerSocket listener = new ServerSocket(port);
    			Socket server;
    			server = listener.accept();
    		      MultiThread connecting = new MultiThread(server,bank);
    		      Thread t = new Thread(connecting);
    		      t.start();
     
    		        listener.close();
            } catch (IOException e) {e.printStackTrace();		}
     
        }
    }

    and the Threaded class
    public class MultiThread implements Runnable {
     private static Socket server;
    public static ArrayList<Branch> bank;
    public MultiThread(Socket socket, ArrayList<Branch> banks) {
        	       this.server=socket;
        	        this.bank=banks;
        	    }
     
    public void run() {
     
        	try {
        		 while (true) {
             	 DataInputStream in =new DataInputStream(server.getInputStream());
                	 DataOutputStream out = new DataOutputStream(server.getOutputStream());
     
                	 String inMess=in.readUTF();
                    if(request is A){
                           //Do something here
                     }
                     else if (request is B){
                           //Do something different
                     }
                   }//while
                  } //try
             catch (IOException ex) {  System.out.println("Problem in message reading");
                }
     
        }
    It seems to be working ok, at least with a single thread, have to finish up the client and be able to upload the server online in order to check it on muliple clients.

    I am slightly troubled about the Branch Objects. They seem to be working ok, but i am not sure i coded it ok.
    Branch is a class defining the objects for bank branches.
    Class UserInterfaceThread is using that class to create objects and allowing user to add more banks, like so:
    import java.util.ArrayList;
    public class UserInterfaceThread extends Thread{ 
    	ArrayList<Branch> banks = new ArrayList<Branch>();
     
    	 public void run() {
                    //objects of Branch for testing purposes
     
    		 banks.add(new Branch("city","Alpha","a1"));
    		 banks.add(new Branch("city","Alpha","a2"));
    		 banks.add(new Branch("city","Alpha","b1"));
    		 banks.add(new Branch("city","Alpha","b2"));
     
    		while (true){
    			System.out.println("press 1 for new branch");
    			String input =System.console().readLine();
    			System.out.println(input);
    			if (input.equals("1")){
    				System.out.println("branch name");
    				 input = System.console().readLine();			
    			banks.add(new Branch("city","bank",input));
    			}
    			else{
    				System.out.println("error");
    			}
    		}//while		
    	 }//run	 
    	 public ArrayList<Branch> getBanks(){
    		 return banks;
    	 }
    }
    So, i am calling this class only at main, cos otherwise it would recreate the objects every time the thread was started. But because i need the objects on the threaded class, i pass it as parameter on the constructor. Again, it seems to be working all right, but if you see something that can be coded better pls let me know

    Quote Originally Posted by jdv View Post
    My advice is to look at Java WebSockets for this sort of thing.
    I am not sure what is the difference with just Sockets, will look it up and see.

    Thanks, ilias

  15. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with a client server program

    It seems to be working ok, at least with a single thread,
    What happens with multiple clients?
    How does this look 2 u?
    This size of code requires execution to see if it works. Too big to just use the eyeball.
    If you don't understand my answer, don't ignore it, ask a question.

  16. #15
    Junior Member
    Join Date
    Aug 2014
    Posts
    29
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Help with a client server program

    I can not test it for multiple clients just yet.
    The client is an android app, and so far i have been testing using an emulator on local host.
    Will have to get it on line on some server(still have a problem with that) in order to properly test it with multiple android cliients.
    Did you understand what i am trying to do with the branch class? Does it seem ok?

  17. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with a client server program

    Did you understand what i am trying to do with the branch class?
    No.
    If you don't understand my answer, don't ignore it, ask a question.

  18. #17
    Forum VIP
    Join Date
    Jun 2011
    Posts
    317
    My Mood
    Bored
    Thanks
    47
    Thanked 89 Times in 74 Posts
    Blog Entries
    4

    Default Re: Help with a client server program

    Quote Originally Posted by skarosg3 View Post
    My initial question was can i use html server to ask from the server any kind of information, or i have to use the technic i mention on my first post?
    If I may, I'd like to take a step back from the code and talk about server theory. There are a lot of acronyms and paradigms surrounding servers but ultimately they all fall into one of two broad categories; services and streams. For streams, think a continuos flow of information; games, maps and real-time data. For services think discrete chunks of information; websites, database queries, a list of Facebook friends.

    It sounds to me that you want a service. The client requests something from the server and receives a result. Alternatively the client updates the server with a package of information and the server updates it's internal state.

    If this feels like what you need start reading up on RESTful web services. Here is how they work:

    • The server exposes resources on top of the HTTP stack. In lay terms an address such as http://www.mydomain.com/people will respond to this URI request with information about people.
    • The client sends standard HTTP headers such as GET or POST with parameters for the server, such as the name of the person the client is interested in.
    • The server responds to the clients request. Typically the response is JSON for cross platform compatibility but it can be anything; XML, CVS, binary, it really doesn't matter.


    REST servers are pretty cool. They are stateless and loosely coupled with the client. So at any point in time, any client (Android, iOS or standard website) can request or update data with only one client side consideration; was the request successful or wasn't it. They are also indempotent meaning it will respond with the same result no matter how often the call is made.

    However, in the industry these web services are typically written in PHP or ASP.NET. I have zero experience with a Java RESTful web service so my advice on the matter ends here.
    Computers are fascinating machines, but they're mostly a reflection of the people using them.
    -- Jeff Atwood

  19. The Following User Says Thank You to ChristopherLowe For This Useful Post:

    Norm (August 30th, 2014)

Similar Threads

  1. my encrypting simple client to server program unable to get the key from client
    By Paytheprice in forum What's Wrong With My Code?
    Replies: 11
    Last Post: February 3rd, 2013, 07:15 AM
  2. [SOLVED] Help ending client program from the server
    By Chromejuice in forum Java Networking
    Replies: 0
    Last Post: October 30th, 2012, 11:28 AM
  3. Help with JAVA Server-Client Program
    By GodLeoBouki in forum Java Theory & Questions
    Replies: 3
    Last Post: April 12th, 2011, 04:35 PM
  4. Client Server Program Not Working
    By ROHIT C. in forum Java Networking
    Replies: 3
    Last Post: September 3rd, 2010, 02:30 PM
  5. Client-Server program
    By Reztem in forum What's Wrong With My Code?
    Replies: 0
    Last Post: May 12th, 2010, 05:36 PM