2

I'm Playing with a simple Client and Server application using socket, and i attempt to print a message in the console and get a response from the server but nothing shows up, i'm fairly new to sockets so i assume i have a logical error. It's a simple app that i want the client to prompt a user a user for a command (in my case an input string where the server will perform an action based on the 'thcharacter), send it to the server and just display the server response.I'm pretty sure my client isn't correct, can someone points out why i can't write anything from the client console.

 package socketProgramming;
        import java.io.*;
        import java.net.*;

 public class MyClient {

        @SuppressWarnings("resource")
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Socket socket= new Socket(); 
            BufferedReader in = null;
            String msg;
            int port = 2222;

            try {

                System.out.println("CLient wants to connect on port: "+port);

                socket = new Socket(InetAddress.getLocalHost().getHostAddress(), port);
                System.out.println("The client is connected");
            } catch (UnknownHostException e) {
                        System.exit(1);
            } catch (IOException e) {
                    System.out.println("connect failed");
                        System.exit(1);
            }

            try{
                 BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    PrintStream output = new PrintStream(socket.getOutputStream());
                  String text = null;
            output.print(text);

            while ((text = input.readLine()) != null){
                System.out.println("Client "+text);

            }


                socket.close();
                System.out.println("Client Exiting");
            }
            catch(IOException e) {
                System.out.println(e);
            }}


        }

package socketProgramming;

import java.io.*;
import java.net.*;



public class MyServer {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub

        String msg = "";
        ServerSocket sSocket = null;
        Socket clientSocket;
        int port = 2222;//Integer.parseInt(args[0]);
        try{
            sSocket = new ServerSocket(port);   

        } catch(IOException e){
            System.out.println(e);
        }

        while(true){
            try {// listen for a connection from client and accept it.
                System.out.println("Server is listenning on host: "
                        +InetAddress.getLocalHost().getHostAddress() +""
                                + " and on port: "                  
                                + port);

                clientSocket = sSocket.accept();
                System.out.println("Connection accepted");
                BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

               // PrintWriter out =
                       // new PrintWriter(clientSocket.getOutputStream(), true);

                PrintStream output = new PrintStream(clientSocket.getOutputStream());

                msg = input.readLine();
                if(msg != null){
                    if(msg.charAt(12)=='4'){

                        System.out.println("reading message "+msg+" ");
                        output.print("Bye");
                        sSocket.close();
                        System.out.println("Server exits");
                    }else{
                        if(msg.charAt(12)=='0'){

                            System.out.println("reading message "+msg+" ");
                            output.print("OK");
                        }else if (msg.charAt(12)=='1'){

                            System.out.println("reading message "+msg+" ");

                            //Should return IP address
                            output.print(clientSocket.getInetAddress());
                        }else if (msg.charAt(12)=='2'){

                            System.out.println("reading message "+msg+" ");
                            for(int i = 1; i<=10; ++i){

                                output.print(i);
                                output.print(" ");
                                }

                            }else if (msg.charAt(12)=='3'){


                                System.out.println("reading message "+msg+" ");
                                output.print("GOT IT");


                            }else{
                                System.out.println("*******************");
                            }

                        }



                    }
                    sSocket.close();
                    System.out.println("Server exits");
                }



            catch(IOException e) {
               System.out.println("accept failed");
               System.exit(1);
            }

        System.out.println("Hello world");
    }


    }
    }
3
  • Can you elaborate who is suppose to start the message and how? Commented Oct 29, 2015 at 3:15
  • If he client send something like CCCCCCCC type0 4567322 X since the 12th char is 0 print Bye or anything. hope it's a little more clear Commented Oct 29, 2015 at 3:20
  • Well, I believe I found the answer to the socket problem. You may still have issues because printing a null string results in a "null" string, but hopefully you diagnose any further problems. Commented Oct 29, 2015 at 3:47

2 Answers 2

2

I took some liberties with your code and changed it a bit. It is by no means a perfect version of what you've supplied; however, it should get you pointed in the right direction. These were the problems that were solved:

  • MyClient was never prompting for user input.
  • MyServer was sending strings without newlines. MyClient was expecting strings with newlines.
  • In MyServer, the main socket was being closed at the bottom of the loop. I believe you intended to close the client socket so that the server would loop around and process another client.
  • In MyServer, you're checking the 13th character of the user's input (because you were indexing the 12th byte (zero based) of the string. I put in brute-force protection against checking the 13th byte of strings that are too short.
  • Again, I simply corrected certain problems in your code. I may have altered it beyond what your true goals actually are. These examples are intended to get you going on your way...

MyClient.java:

import java.io.*;
import java.net.*;

public class MyClient {

  @SuppressWarnings("resource")
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    Socket socket = new Socket();
    int port = 2222;

    try {

      System.out.println("CLient wants to connect on port: " + port);

      socket = new Socket(InetAddress.getLocalHost().getHostAddress(), port);
      System.out.println("The client is connected");
    } catch (UnknownHostException e) {
      System.exit(1);
    } catch (IOException e) {
      System.out.println("connect failed");
      System.exit(1);
    }

    try {
      BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      PrintStream output = new PrintStream(socket.getOutputStream());

      // Get a line of input from the user.
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      String inputFromUser = br.readLine();

      // Send that line of input to MyServer.
      output.println(inputFromUser);

      // Print out the response from MyServer.
      System.out.println("SERVER RESPONSE: " + input.readLine());

      socket.close();
      System.out.println("Client Exiting");
    } catch (IOException e) {
      System.out.println(e);
    }
  }

}

MyServer.java:

import java.io.*;
import java.net.*;

public class MyServer {

  public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub

    String msg = "";
    ServerSocket sSocket = null;
    Socket clientSocket;
    int port = 2222;// Integer.parseInt(args[0]);
    try {
      sSocket = new ServerSocket(port);

    } catch (IOException e) {
      System.out.println(e);
    }

    while (true) {
      try {// listen for a connection from client and accept it.
        System.out.println("Server is listenning on host: " + InetAddress.getLocalHost().getHostAddress() + "" + " and on port: "
            + port);

        clientSocket = sSocket.accept();
        System.out.println("Connection accepted");
        BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

        // PrintWriter out =
        // new PrintWriter(clientSocket.getOutputStream(), true);

        PrintStream output = new PrintStream(clientSocket.getOutputStream());

        msg = input.readLine();
        if (msg != null) {
          if (msg.length() > 12 && msg.charAt(12) == '4') {

            System.out.println("reading message " + msg + " ");
            output.println("Bye");
            System.out.println("Server exits");
          } else {
            if (msg.length() > 12 && msg.charAt(12) == '0') {

              System.out.println("reading message " + msg + " ");
              output.println("OK");
            } else if (msg.length() > 12 && msg.charAt(12) == '1') {

              System.out.println("reading message " + msg + " ");

              // Should return IP address
              output.println(clientSocket.getInetAddress());
            } else if (msg.length() > 12 && msg.charAt(12) == '2') {

              System.out.println("reading message " + msg + " ");
              for (int i = 1; i <= 10; ++i) {

                output.println(i + " ");
              }

            } else if (msg.length() > 12 && msg.charAt(12) == '3') {

              System.out.println("reading message " + msg + " ");
              output.println("GOT IT");

            } else {
              System.out.println("*******************");

              // Invalid question from client, I guess.
              output.println("HUH?");
            }

          }

          // Make sure output is flushed to client.  It will be, but
          // just in case...
          output.flush();
        }

        // We're done with this client.  Close his socket.
        clientSocket.shutdownOutput();
        clientSocket.close();
        System.out.println("Closed client socket");
      }

      catch (IOException e) {
        System.out.println("accept failed");
        e.printStackTrace();
        System.exit(1);
      }

      System.out.println("Hello world");
    }

  }
}
Sign up to request clarification or add additional context in comments.

Comments

2

The problem is that nobody is actually sending any lines. This is what your client does:

output.print(text); //sends null
while ((text = input.readLine()) != null){ //waits to receive a line

This last part is where your client stops because it waits for input that the server never sends. So here is where the server stops:

msg = input.readLine(); //waits to recieve a line

It never reads in null because you didn't send a line (e.g. ending with '\n'). You can easily fix this problem by replacing your output.print() calls with output.println() calls, so that your readers know the line has end and can be read in now.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.