Results 1 to 11 of 11
  1. #1
    nevinvj24 is offline Member
    Join Date
    Nov 2013
    Posts
    6
    Rep Power
    0

    Post Need Help! Java Client/Server. Sending user's input to server, issue with while loop

    I just started with Java some weeks back. Very interesting language! Now I am trying to develop a simple client/server application. I have an issue when I want to put the codes to: (1) read user input, (2) send it to the server for processing and (3) displaying the result on the console in a while loop. When I enter the string "stop" normally the client must terminate the program, but it doesn't. I spent hours to figure out what is wrong, but could not understand. Please check the codes below:

    ******************************************CLIENT** *******************************************
    Java Code:
    import java.io.*;
    import java.net.*;
    
    public class objClient {
        public static void main(String argv[]) throws Exception {
            String sentence;
            String modifiedSentence;
            BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
    
            Socket clientSocket = new Socket("localhost", 12345);
            DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
            BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            
            sentence = inFromUser.readLine();
            
            while ( sentence != "stop")
            {
                outToServer.writeBytes(sentence + '\n');
                modifiedSentence = inFromServer.readLine();
                System.out.println(modifiedSentence+'\n');
                sentence = inFromUser.readLine();
                System.out.println("new->"+sentence+'\n');
            }
            clientSocket.close();
        }
    }
    ******************************************SERVER** *******************************************
    Java Code:
    import java.io.*;
    import java.net.*;
    
    public class objServer {
        public static void main(String args[]) throws Exception {
            String clientSentence;
            String capitalizedSentence;
            ServerSocket welcomeSocket = new ServerSocket(12345);
    
            while(true) {
                Socket connectionSocket = welcomeSocket.accept();
                BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
                DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
                clientSentence = inFromClient.readLine();
                capitalizedSentence = clientSentence.toUpperCase() + '\n';
                outToClient.writeBytes(capitalizedSentence);
            }
        }
    }
    ************************************************** ************************************************** ***
    Last edited by nevinvj24; 05-17-2014 at 03:39 PM.

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,902
    Rep Power
    25

    Default Re: Need Help! Java Client/Server. Sending user's input to server, issue with while l

    Please edit your post and wrap your code with code tags:
    [code]
    YOUR CODE HERE
    [/code]
    to get highlighting and preserve formatting.

    Use the equals() method for comparing Strings, not the == operator.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    nevinvj24 is offline Member
    Join Date
    Nov 2013
    Posts
    6
    Rep Power
    0

    Default Re: Need Help! Java Client/Server. Sending user's input to server, issue with while l

    I changed
    Java Code:
    sentence != "stop"
    to
    Java Code:
    !sentence.equals("stop")
    in the client, but it is still not working.

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,902
    Rep Power
    25

    Default Re: Need Help! Java Client/Server. Sending user's input to server, issue with while l

    it is still not working.
    Try debugging the code to see what is happening. Add lots of println() statements that print out the values of the variables as their values are changed. For example what is in the sentence variable? Does it ever have the String: "stop"?
    If you don't understand my response, don't ignore it, ask a question.

  5. #5
    nevinvj24 is offline Member
    Join Date
    Nov 2013
    Posts
    6
    Rep Power
    0

    Default Re: Need Help! Java Client/Server. Sending user's input to server, issue with while l

    Quote Originally Posted by Norm View Post
    For example what is in the sentence variable? Does it ever have the String: "stop"?
    User input is stored in variable sentence.

    Each time the user input a sentence and hit "enter", the sentence variable content is sent to the server for processing (in this example, it is just converting all characters to upper case) and send back the result for display on the client side. And when user input word "stop", the client normally should terminate.
    Last edited by nevinvj24; 05-17-2014 at 04:29 PM.

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,902
    Rep Power
    25

    Default Re: Need Help! Java Client/Server. Sending user's input to server, issue with while l

    User input is stored in variable sentence.
    What is printed by the debugging println()s that I suggested that you add?
    If you don't understand my response, don't ignore it, ask a question.

  7. #7
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    447
    Rep Power
    1

    Default Re: Need Help! Java Client/Server. Sending user's input to server, issue with while l

    Hi,

    can you test and describe the behavior that you see?

    - Directly enter "stop" at the client after start - I think that this is working.
    - Enter something else - do you get the reply in uppercase? Maybe not - the problem here could be, that you do not flush the output stream. Whenever you want to be sure that something is written: Flush the stream!
    - So if you get the result back and enter "stop" - it should still work.
    - If you send something to the server, it no longer works. The reason for this is quite obvious if we write down what the server is doing:
    a) The server opens a Socket for new connections.
    b) inside an endless loop, the server:
    c) waits for an incoming connection (Only now a connection is accepted. And only exactly one!)
    d) The server waits for a line (If that does not come, the server simply waits and is doing nothing else e.g. no more connections are accepted.
    e) when the data is received, it sends some data back.
    f) now everything is forgotten by the server and the server restarts at c. So no more input of a client is accepted.

    The common practice for a server is:

    == blocking calls ==
    The server handles incoming connections in one thread
    For each client, another thread is started to handle the client

    ==unblocking calls ==
    When you use unblocking calls, then you have to check if something must be done. The advantage is, that you no longer need multiple threads (which is in fact a limitation of the server regarding possible number of clients).
    So in a loop you check:
    - are there any new connection requests? If yes: Quickly accept them.
    - Then you loop through all sockets: Is any data there to be received? if yes: Quickly get the data.

    That was just a rough description. If you are interested in Networking with Java I would suggest to read the book Java Network Programming, 4th edition (Oreilly, Author is Elliotte Rusty Harold).

    With kind regards,

    Konrad

  8. #8
    nevinvj24 is offline Member
    Join Date
    Nov 2013
    Posts
    6
    Rep Power
    0

    Default Re: Need Help! Java Client/Server. Sending user's input to server, issue with while l

    Quote Originally Posted by Norm View Post
    What is printed by the debugging println()s that I suggested that you add?
    I did use a lot of println and apparently it helps to see more clearly where the problem was; the client is ok, the issue was from the server script. The following code below should have been outside the while loop:
    Java Code:
    Socket connectionSocket = welcomeSocket.accept();
    BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
    DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
    Now it is working fine.

    I paste below the fully working codes if ever someone someday will be in a similar situation like me today, hope it will help them:

    **********CLIENT**********
    Java Code:
    import java.io.*;
    import java.net.*;
    
    public class objClient {
        public static void main(String argv[]) throws Exception {
            String sentence;
            String modifiedSentence;
            BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
    
            Socket clientSocket = new Socket("localhost", 12345);
            DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
            BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            
        	System.out.println("Enter words: ");
            sentence = inFromUser.readLine();
            
            while (!sentence.equals("stop"))
            {
            	outToServer.writeBytes(sentence + '\n');
            	System.out.println("Sent to the server: "+sentence+'\n');
            	modifiedSentence = inFromServer.readLine();
            	System.out.println("Received from the server: "+modifiedSentence+'\n');
            	System.out.println("Enter words for the 2nd time: ");
                sentence = inFromUser.readLine();
            	System.out.println("Added by the user as second input: "+sentence+'\n');
            }
            clientSocket.close();
        }
    }
    **********SERVER**********
    Java Code:
    import java.io.*;
    import java.net.*;
    
    public class objServer {
        public static void main(String args[]) throws Exception {
            String clientSentence = "";
            String capitalizedSentence = "";
    
            	ServerSocket welcomeSocket = new ServerSocket(12345);
            	Socket connectionSocket = welcomeSocket.accept();
            	BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            	DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
    
            	while(true) {
            		clientSentence = inFromClient.readLine();
            		if (clientSentence==null)
            			break;
            		System.out.println("Received from the client: "+clientSentence+'\n');
            		capitalizedSentence = clientSentence.toUpperCase() + '\n';
            		outToClient.writeBytes(capitalizedSentence);
            		System.out.println("Sent to the client: "+capitalizedSentence+'\n');
            	}//endwhile
        }//main
    }//class
    Just a quick recap about what the application does: It ask the user for an input, send it to the server, do some processing (in this case, it simply changes the characters to upper case) and send back the result to the client. User can input unlimited number of times, and just input "stop" to terminate the application.
    Last edited by nevinvj24; 05-17-2014 at 08:53 PM.

  9. #9
    nevinvj24 is offline Member
    Join Date
    Nov 2013
    Posts
    6
    Rep Power
    0

    Default Re: Need Help! Java Client/Server. Sending user's input to server, issue with while l

    Konrad, though the application was working, when I enter "stop", the server keeps on readLine()
    Java Code:
    clientSentence = inFromClient.readLine();
    and terminate with the "Java Lang Null pointer exception" error. To get around this, I just add these two lines
    Java Code:
    if (clientSentence==null) break;
    to check if a null is being read so as to avoid processing it and get the java lang null pointer exception error.

    This is my way around as an amateur. Is there a better way to avoid the error?

    Thanks.

  10. #10
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    447
    Rep Power
    1

    Default Re: Need Help! Java Client/Server. Sending user's input to server, issue with while l

    Hi,

    that null check is correct. When the connection is closed readLine will return null. So your approach so far is correct.

    So your server is opening a socket, accept exactly one connection and afterwards ends, too. That is a good start already but normally a server is an application that is waiting for clients all the time. And that can handle multiple clients at the same time. Maybe you want to extend your Server so it can do that? The steps for this could be:
    a) Move the handling of the client itself into a Class that implements Runnable. (So it needs the socket that comes back from the accept call and then does exactly what you did so far. (Maybe add some close() calls to cleanup.)
    b) Your main thread will have a loop that accepts sockets and starts the client threads

    But all this depends on what you want to build of course.

    With kind regards,

    Konrad

  11. #11
    nevinvj24 is offline Member
    Join Date
    Nov 2013
    Posts
    6
    Rep Power
    0

    Default Re: Need Help! Java Client/Server. Sending user's input to server, issue with while l

    Quote Originally Posted by kneitzel View Post
    The steps for this could be:
    a) Move the handling of the client itself into a Class that implements Runnable. (So it needs the socket that comes back from the accept call and then does exactly what you did so far. (Maybe add some close() calls to cleanup.)
    b) Your main thread will have a loop that accepts sockets and starts the client threads
    Hi Konrad,

    Thanks for the suggestions. I guess you are right to create a class that implements Runnable as a next step to advance this simple application.

    I will be looking into that as from tomorrow.

    Best,
    Nevin

Similar Threads

  1. Replies: 0
    Last Post: 10-05-2013, 06:51 AM
  2. Replies: 1
    Last Post: 04-19-2013, 11:13 AM
  3. Java MultiClient Server and Client Sending Issues
    By hunter2379 in forum Networking
    Replies: 0
    Last Post: 03-05-2013, 05:46 AM
  4. having issue with user input and using while loop
    By barqcider in forum New To Java
    Replies: 4
    Last Post: 10-09-2012, 02:06 AM
  5. Replies: 4
    Last Post: 09-29-2011, 02:17 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •