0

I'm trying to create a program where a client and server send text messages to each other (in utf-8 string format) similar to how two phones text message each other. Eventually I will need to create four lines (two to encode/decode utf-8 string on server side) (two to encode/decode utf-8 string on client side) This program uses two threads, one for the client one for the server.

Screenshot of error in mac terminal (command prompt)

enter image description here

There were no errors before I changed the following lines of code:

                        String MessageFromClientEncodedUTF8 = "";
                        BufferedReader BufReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));  
                        socket = serverSocket.accept();    
                        InputStream is = socket.getInputStream();
                        InputStreamReader isr = new InputStreamReader(is);
                        BufferedReader br = new BufferedReader(isr);
                        String MessageFromClientDecodedFromUTF8 = BufReader1.readLine();
                        System.out.println("The message is currently encoded UTF-8");
                        byte[] bytes = MessageFromClientEncodedUTF8.getBytes("UTF-8"); 
                        String MessageFromClientDecodedUTF8 = new String(bytes, "UTF-8");
                        System.out.println("Message received from client (decoded utf-8): "+ MessageFromClientDecodedUTF8);

There are three files: the main function file, the server file, and the client file. When the main function file runs, if the "-l" command line argument is present, the server file will run, otherwise the client will run.

Server file (DirectMessengerServer.java):

import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class DirectMessengerServer
{
    private static Socket socket;
    boolean KeepRunning = true;
    void ServerRun(String[] args)
    {
        Thread Server = new Thread () 
        {
            public void run ()
            {   
                System.out.println("Server thread is now running");
                try
                {
                    System.out.println("Try block begins..");
                    int port_number1= Integer.valueOf(args[1]);
                    System.out.println("Port number is: " + port_number1);
                    ServerSocket serverSocket = new ServerSocket(port_number1);
                    //SocketAddress addr = new InetSocketAddress(address, port_number1);
                    System.out.println( "Listening for connections on port: " + ( port_number1 ) );

                    while(KeepRunning)
                    {
                        //Reading the message from the client
                        String MessageFromClientEncodedUTF8 = "";
                        BufferedReader BufReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));  
                        socket = serverSocket.accept();    
                        InputStream is = socket.getInputStream();
                        InputStreamReader isr = new InputStreamReader(is);
                        BufferedReader br = new BufferedReader(isr);
                        String MessageFromClientDecodedFromUTF8 = BufReader1.readLine();
                        System.out.println("The message is currently encoded UTF-8");
                        byte[] bytes = MessageFromClientEncodedUTF8.getBytes("UTF-8"); 
                        String MessageFromClientDecodedUTF8 = new String(bytes, "UTF-8");
                        System.out.println("Message received from client (decoded utf-8): "+ MessageFromClientDecodedUTF8);
                        //Shut down with zero-length message
                        if(MessageFromClientDecodedFromUTF8.equals(""))
                        {
                            KeepRunning=false;
                            System.out.println("Shutting down");
                            System.exit(0);
                            socket.close();
                            serverSocket.close();
                        }
                        if(MessageFromClientDecodedFromUTF8.equals(null))
                        {
                            KeepRunning=false;
                            System.out.println("Shutting down");
                            System.exit(0);
                            socket.close();
                            serverSocket.close();
                        }
                        if(MessageFromClientDecodedFromUTF8=="")
                        {
                            KeepRunning=false;
                            System.out.println("Shutting down");
                            System.exit(0);
                            socket.close();
                            serverSocket.close();
                        }
                        if(MessageFromClientDecodedFromUTF8==null)
                        {
                            KeepRunning=false;
                            System.out.println("Shutting down");
                            System.exit(0);
                            socket.close();
                            serverSocket.close();
                        }
                        if(MessageFromClientDecodedFromUTF8=="\n")
                        {
                            KeepRunning=false;
                            System.out.println("Shutting down");
                            System.exit(0);
                            socket.close();
                            serverSocket.close();
                        }






                        //creating message to server send from standard input


                        String newmessage = "";
                        try {
                            // input the message from standard input
                            BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
                            String line = "";

                            System.out.println( "Standard input (press enter then control D when finished): " );

                            while( (line= input.readLine()) != null && KeepRunning==true )      
                            {
                                newmessage += line + " \n ";
                            }
                            }
                        catch ( Exception e ) {
                            System.out.println( e.getMessage() );
                        }
                        //Writing return message back to client
                        String returnMessage = newmessage;
                        OutputStream os = socket.getOutputStream();
                        OutputStreamWriter osw = new OutputStreamWriter(os);
                        BufferedWriter bw = new BufferedWriter(osw);
                        bw.write(returnMessage + "\n");
                        System.out.println("Message sent to client: "+returnMessage);
                        bw.flush();




                    }
                }
                catch ( Exception e )
                {
                    e.printStackTrace();

                }  
                finally
                {
                    //Closing the socket
                    try
                    {
                        socket.close();


                    }
                    catch(Exception e)
                    {
                        e.printStackTrace();
                    }
                }

            }

        };
        Server.start();
    }
}

Client file (DirectMessengerClient.java):

import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class DirectMessengerClient
{
    boolean KeepRunning = true;
    private static Socket socket;
    //static String[] arguments;
    //public static void main(String[] args)
    //{
    //  arguments = args;
    //}
    public DirectMessengerClient()
    {

        //System.out.println("test.");

    }
    public void ClientRun(String[] args)
    {
        Thread Client = new Thread ()
        {
          public void run()
          {   
                System.out.println("Client thread is now running");

                    try
                    {
                            System.out.println("Try block begins..");
                            String port_number1= args[0];
                            System.out.println("Port number is: " + port_number1);
                            int port = Integer.valueOf(port_number1);
                            System.out.println("Listening for connections..");
                            System.out.println( "Listening on port: " + port_number1 );

                            while(KeepRunning)
                            {
                                String host = "localhost";
                                InetAddress address = InetAddress.getByName(host);
                                socket = new Socket(address, port);


                                //Send the message to the server
                                OutputStream os = socket.getOutputStream();
                                OutputStreamWriter osw = new OutputStreamWriter(os);
                                BufferedWriter bw = new BufferedWriter(osw);

                                //creating message to send from standard input
                                String newmessage = "";
                                try 
                                {
                                    // input the message from standard input
                                    BufferedReader input= new BufferedReader( 
                                    new InputStreamReader(System.in));
                                    String line = "";

                                    System.out.println( "Standard input (press enter then control D when finished): " );

                                    while( (line= input.readLine()) != null )       
                                    {
                                        newmessage += line + " ";
                                    }

                                }
                                catch ( Exception e )
                                {
                                    System.out.println( e.getMessage() );
                                }
                                String sendMessage = newmessage;
                                bw.write(sendMessage + "\n"); // <--- ADD THIS LINE
                                bw.flush();
                                System.out.println("Message sent to server: "+sendMessage);

                                //Get the return message from the server
                                InputStream is = socket.getInputStream();
                                InputStreamReader isr = new InputStreamReader(is);
                                BufferedReader br = new BufferedReader(isr);
                                String MessageFromServer = br.readLine();
                                System.out.println("Message received from server: " + MessageFromServer);
                                 if(MessageFromServer.equals(""))
                                 {
                                    KeepRunning=false;
                                    System.out.println("Shutting down");
                                    System.exit(0);
                                    socket.close();
                                 }
                                 if(MessageFromServer.equals(null))
                                 {
                                    KeepRunning=false;
                                    System.out.println("Shutting down");
                                    System.exit(0);
                                    socket.close();
                                 }
                                 if(MessageFromServer=="")
                                 {
                                    KeepRunning=false;
                                    System.out.println("Shutting down");
                                    System.exit(0);
                                    socket.close();
                                 }
                                 if(MessageFromServer==null)
                                 {
                                    KeepRunning=false;
                                    System.out.println("Shutting down");
                                    System.exit(0);
                                    socket.close();
                                 }
                                 if(MessageFromServer=="\n")
                                 {
                                    KeepRunning=false;
                                    System.out.println("Shutting down");
                                    System.exit(0);
                                    socket.close();
                                 }
                            }
                }

                catch ( Exception e )
                {
                    e.printStackTrace();
                }

                finally
                {
                    //Closing the socket
                    try
                    {
                        socket.close();
                    }
                    catch(Exception e)
                    {
                        e.printStackTrace();
                    }
                }

          }
        };

    Client.start(); 
    }
}

Main function file (DirectMessengerCombined.java):

public class DirectMessengerCombined
{
    public static void main(String[] args)
    {
        DirectMessengerClient Client1 = new DirectMessengerClient();
        DirectMessengerServer Server1 = new DirectMessengerServer();
          for (int i = 0; i < args.length; i++)
          {
                if(!args[0].equals("-l"))
                {
                    Client1.ClientRun(args);
                }
                switch (args[0].charAt(0))
                {
                    case '-':
                    if(args[0].equals("-l"))
                    {   
                        Server1.ServerRun(args);
                    }

                }
           i=args.length + 20;
          } 
    }

}

My question is: How do I change the way the strings are encoded or decoded in order to send strings to the other side or how to solve the null pointer exception error?

  • 1
    What is line 30 of DirectmessengerServer? – Steve Smith Apr 10 '17 at 15:51
  • @SteveSmith I believe it is the BufferedReader BufReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8")); –  Apr 10 '17 at 15:52
  • You cannot call `socket.getInputStream()` before assigning a value to `socket`. – VGR Apr 10 '17 at 15:53
  • @VGR then the solution is to move the line socket = serverSocket.accept(); above the BufferedReader BufReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8")); line correct? –  Apr 10 '17 at 15:56
  • @Eric, That's exactly what I put in my answer :) `These two lines should be the other way around.`. – Steve Smith Apr 10 '17 at 15:58

1 Answers1

1

It is because you are trying to get the inputstream of a socket before it exists:-

   BufferedReader BufReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));  
   socket = serverSocket.accept();

These two lines should be the other way around. :)

EDIT: Looking further at your code, you are creating BufReader1 (which is causing the error) and then creating br in exactly the same way, i.e. both are a BufferedReader of the socket. You only need one; having two will probably cause problems for the readers.

Steve Smith
  • 2,244
  • 2
  • 18
  • 22