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 5 of 5

Thread: Problem with communicating between client and server sockets in Java

  1. #1
    Junior Member
    Join Date
    Mar 2014
    Posts
    8
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Problem with communicating between client and server sockets in Java

    Hi, i'm working on an assignment right now which involves passing a variable series of numbers to the Server to be sorted into the correct order and returned to the client.

    So far I have it connecting to the server and asking for my numbers, and I am entering each number and pressing return, and it is accepting each number individually.

    One (smaller I think) problem i'm having is with the client code, specifically the while loop.. I've tried to code it so that when I enter a full stop ('.') the program will stop asking me for more numbers and move on to sending them to the server.. but instead it just crashes giving an error.. heres an example

    "Enter a number: 1
    Enter a number: 3
    Enter a number: 2
    Enter a number: 1.
    java.lang.NumberFormatException: For input string: "1."
    at java.lang.NumberFormatException.forInputString(Num berFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:492)
    at java.lang.Integer.parseInt(Integer.java:527)
    at numberSortprogram.NumSortClient.main(NumSortClient .java:38)'"



    If anyone can see the problem here please let me know


    here's the client code in full

    package numberSortprogram;
    import java.io.*;
    import java.net.ServerSocket;
     
    public class NumSortClient {
     
    	public static void main(String[] args) {
    	      InputStreamReader is = new InputStreamReader(System.in);
    	      BufferedReader br = new BufferedReader(is);
     
    	      try {
    	         System.out.println("Welcome to the Integer Sorting Client.\n" +
    	            "What is the name of the server host?");
    	         String hostName = br.readLine();
    	         if (hostName.length() == 0) // if user did not enter a name
    	            hostName = "localhost";  //   use the default host name
    	         System.out.println("What is the port number of the server host?");
    	         String portNum = br.readLine();
     
    	         if (portNum.length() == 0)
    	            portNum = "4444";          // default port number
    	         numSortclientHelper helper = new numSortclientHelper(hostName, portNum);    
    	         System.out.println("Enter your list of numbers <return>");
     
    	        int [] numbersArray = new int[20]; 
     
    	        int i=0; 
    	        while (i < numbersArray.length) {
    	        	System.out.print("Enter a number: ");
    	        	numbersArray[i]=Integer.parseInt(br.readLine());
     
    	        	if (i == '.') {
    	        		break;
    	        	}
    	        }
    	        String stringArray = numbersArray.toString();
    	        // sent the number to the server
     
    	         helper.sendNumber(stringArray);
    	         System.out.println("The numbers have been sent to the server for sorting"); 
    	         // now read the individual integers from the server
    	     	int sortedArray = helper.receiveNumber();
     
    	     	for(int i1= 0; i1 < sortedArray; i1++){
    	     		int splitArray = helper.receiveNumber();
    	     		System.out.println(splitArray);
     
    	     	}
    	         System.out.println("Numbers in ascending order are:-");
    	         //  helper.receiveNumber(splitArray);
     
    	         System.out.println("Session Over ");
    	         helper.done();
    	      } // end try  
     
    	      catch (Exception ex) {
    	         ex.printStackTrace( );
    	      } //end catch
    	   } //end main
     
    	} // end numSortclient class

    I'll bump the post with my other problem so it's not a great big wall of text. Thanks if you took the time to read this

    --- Update ---

    Continued: the big problem that I have is figuring out how to send the sorted array back to the client..

    So, what im trying to get to happen is-

    -Client is asked to enter numbers
    -Client enters series of numbers into an array
    -Array is converted to a string and sent to the server
    -String is then split into an array of strings and sorted using compareTo (don't know if this is the best way?)
    -Sorted array is sent back to client and displayed.

    fyi this is making use of streamsockets..

    All of the rest of my code is below:
    Server code

    package numberSortprogram;
     
    import java.io.IOException;
    import java.net.*;
    import java.util.regex.PatternSyntaxException;
     
     
    public class NumSortServer {
     
       public static void main(String[] args) {
          int serverPort = 4444;    // default port
          if (args.length == 1 )
             serverPort = Integer.parseInt(args[0]);       
          try {
             // instantiates a stream socket for accepting connections
           @SuppressWarnings("resource")
    	ServerSocket myConnectionSocket = new ServerSocket(serverPort); 
           System.out.println("Number sorting server ready.");  
     
           while (true) {  // forever loop
                // wait to accept a connection 
                System.out.println("Waiting for a connection.");
                @SuppressWarnings("resource")
    			MyStreamSocketClient myDataSocket = new MyStreamSocketClient(myConnectionSocket.accept( ));
                System.out.println("Connection Accepted");
     
                // Receive the list of numbers from client
                String stringArray = myDataSocket.receiveMessage(); // read incoming values
     
                try {
                    String[] splitArray = stringArray.split("\\s+");
     
                    String tempVar;
                    for (int i = 0; i < splitArray.length; i++)
                    {
                           for(int j = 0; j < splitArray.length; j++)
                           {
                                    if(splitArray[i].compareTo(splitArray[j + 1])<0)
                                    {
                                           tempVar = splitArray [j];
                                           splitArray [j]= splitArray [i];
                                           splitArray [i] = tempVar;
                                    }
                           }
                    }
                    for (int i = 0; i < splitArray.length; i++)
                    {
                       System.out.println(splitArray[i].toString());
                    } 
                } catch (PatternSyntaxException ex) {
                }
     
           }
          } catch (IOException e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    	} finally {
       }
       }
    }

    ClientHelper Code

    package numberSortprogram;
    import java.net.*;
    import java.io.*;
     
     
    public class numSortclientHelper {
    	private MyStreamSocketClient mySocket;
    	   private InetAddress serverHost;
    	   private int serverPort;
     
    	   numSortclientHelper(String hostName,String portNum) throws SocketException, UnknownHostException, IOException {                               
    	       this.serverHost = InetAddress.getByName(hostName);
    	       this.serverPort = Integer.parseInt(portNum);
    	       //Instantiates a stream-mode socket and wait for a connection.
    	       this.mySocket = new MyStreamSocketClient(this.serverHost, this.serverPort); 
    	       System.out.println("Connection request made");
    	   } // end constructor
     
    	   public void sendNumber( String stringArray) throws SocketException, IOException{        
    	      mySocket.sendMessage( stringArray);
    	    } //end SendNumber   
     
    	    public int  receiveNumber() throws SocketException, IOException{        
    	      String splitArray = mySocket.receiveMessage();
    	      return Integer.parseInt(splitArray, 20);
    	    } //end receiveSum  
     
     
    	  public void done( ) throws SocketException, IOException{
    	      mySocket.close( );
    	   } // end done 
     
     
    }

    StreamSocket Code

    package numberSortprogram;
     
    import java.net.*; 
    import java.io.*;
     
    /**
     * A wrapper class of Socket which contains 
     * methods for sending and receiving messages
     */
    public class MyStreamSocketClient extends Socket {
       private Socket  socket;
       private BufferedReader input;
       private PrintWriter output;
     
       MyStreamSocketClient(InetAddress acceptorHost, int acceptorPort ) throws SocketException, IOException{
          socket = new Socket(acceptorHost, acceptorPort );
          setStreams( );
     
       }
     
       MyStreamSocketClient(Socket socket)  throws IOException {
          this.socket = socket;
          setStreams( );
       }
     
       private void setStreams( ) throws IOException{
          // get an input stream for reading from the data socket
          InputStream inStream = socket.getInputStream();
          input = new BufferedReader(new InputStreamReader(inStream));
          OutputStream outStream = socket.getOutputStream();
          // create a PrinterWriter object for character-mode output
          output = new PrintWriter(new OutputStreamWriter(outStream));
       }
     
       public void sendMessage(String stringArray) throws IOException {	
          output.println(stringArray);   
          //The ensuing flush method call is necessary for the data to
          // be written to the socket data stream before the
          // socket is closed.
          output.flush();               
       } // end sendMessage
     
       public String receiveMessage( ) throws IOException {	
          // read a line from the data stream
          String message = input.readLine( );  
          return message;
       } //end receiveMessage
     
    } //end class


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,337
    Thanks
    182
    Thanked 830 Times in 773 Posts
    Blog Entries
    5

    Default Re: Problem with communicating between client and server sockets in Java

    ava.lang.NumberFormatException: For input string: "1."
    I recommend reading the API for methods you are using that the stack trace indicates:
    Integer (Java Platform SE 7 )
    The period at the end of this String cannot be parsed into a number, and will cause a NumberFormatException when attempting to parse it.

  3. #3
    Junior Member
    Join Date
    Mar 2014
    Posts
    8
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Problem with communicating between client and server sockets in Java

    Quote Originally Posted by copeg View Post
    I recommend reading the API for methods you are using that the stack trace indicates:
    Integer (Java Platform SE 7 )
    The period at the end of this String cannot be parsed into a number, and will cause a NumberFormatException when attempting to parse it.
    does this mean I need to use a number to end the input?

    i thought not since the data im entering is composed of all numbers

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,100
    Thanks
    52
    Thanked 2,285 Times in 2,256 Posts

    Default Re: Problem with communicating between client and server sockets in Java

    The code could read the input as a String and test for the "." before trying to convert it to an int.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,337
    Thanks
    182
    Thanked 830 Times in 773 Posts
    Blog Entries
    5

    Default Re: Problem with communicating between client and server sockets in Java

    Quote Originally Posted by hcoyle545 View Post
    does this mean I need to use a number to end the input?

    i thought not since the data im entering is composed of all numbers
    If your client has two tasks - 1) parse numbers 2) move on when it encounters a the termination character (.) - your client code must anticipate either (or both). My advice: parse the input to look for both numbers and termination chars. Parse any numbers before the termination char, and move on if termination char is encountered

Similar Threads

  1. Replies: 2
    Last Post: February 4th, 2014, 09:19 AM
  2. java Client Server program by using socket problem
    By Mad Engineer in forum What's Wrong With My Code?
    Replies: 3
    Last Post: July 31st, 2013, 10:57 AM
  3. Problems with sockets on simple server and client programs.
    By gongshow20 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: May 24th, 2013, 09:17 PM
  4. sending images client/server sockets
    By devett in forum Java Networking
    Replies: 7
    Last Post: June 7th, 2011, 08:38 AM
  5. Replies: 1
    Last Post: March 23rd, 2010, 02:29 AM