Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / August 2005

Tip: Looking for answers? Try searching our database.

Threads java.lang.NullPointerException

Thread view: 
Max010 - 22 Aug 2005 09:39 GMT
Hi there I was wondering if anyone can help me please.

I ve been working on a simple chat server program and it works when the
server handles one client at the time.  I ve been trying to make the
server able to answer clients requests at the same time with threads.

I always get the same error message when I run the server:

java.lang.NullPointerException

at chatserverq3.ServerGUI.processClientRequests(ServerGUI.java:113)

    at chatserverq3.ServerGUI.run(ServerGUI.java:73)

    at java.lang.Thread.run(Thread.java:484)

This is the client code:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

public class ClientGUI extends JFrame implements ActionListener
{
 private JTextField nameField;
 private JLabel nameLabel;
 private JLabel areaLabel;
 private JPanel topPanel, botPanel;
 private JButton connectButton;
 private JTextArea listArea;

 private InputStream is;
 private OutputStream os;
 private BufferedReader fromServer;
 private Socket socket;
 private PrintWriter toServer;

 static final String SERVER_ADDRESS = "127.0.0.1";
 static final int SERVER_PORT_NUMBER = 4000;
 static final String CLIENT_LOGGINGOFF = "Exit";

//constructor for the client GUI
 public ClientGUI(String title)
 {
  setSize(400, 400);
  setTitle(title);
  setLocation(100, 100);
  nameLabel = new JLabel("Name");
  nameField = new JTextField(10);
  areaLabel = new JLabel("Connected Users");
  topPanel = new JPanel();
  topPanel.setLayout(new BorderLayout());
  botPanel = new JPanel();
  connectButton = new JButton("Connect");
  connectButton.addActionListener(this);
  listArea = new JTextArea(10, 30);
  JScrollPane scr = new JScrollPane(listArea);

  topPanel.add(nameField, "West");
  topPanel.add(nameLabel, "Center");
  topPanel.add(connectButton, "East");

  botPanel.add(areaLabel);
  botPanel.add(listArea);

  getContentPane().add(topPanel, "North");
  getContentPane().add(botPanel, "Center");

  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 }

 //attempts to connect the client to the server
 private void connectServer()
 {
  try
   {
    socket = new Socket(SERVER_ADDRESS, SERVER_PORT_NUMBER);
    openStreams();
   }
   catch(IOException e)
     {
       System.out.println("Trouble contacting the server " + e);
     }
  }

 private void open()throws IOException
 {
  final boolean AUTO_FLUSH = true;
  is = socket.getInputStream();
  fromServer = new BufferedReader(new InputStreamReader(is));
  os = socket.getOutputStream();
  toServer = new PrintWriter(os, AUTO_FLUSH);
 }

//action performed when the client GUI button is pressed
public void actionPerformed(ActionEvent a)
 {
  String buttonLabel = connectButton.getText();
  String userName = nameField.getText();
  try
  {
   if((buttonLabel == "Connect")&&(userName.length()> 0))
     {
      connectToServer();
      sendUserName(userName);
      connectButton.setText("Disconnect");
     }
     else
     {
       logOff(userName);
       connectButton.setText("Connect");
     }

   }
   catch(IOException e)
     {
       System.out.println("Problem with the server " + e);
     }
  }

 private void close()throws IOException
 {
  toServer.close();
  os.close();
  fromServer.close();
  is.close();
 }

 //sends the user name to the server
 private void sendUserName(String aName)throws IOException
 {
  String reply;
  String uName = aName;
  toServer.println(uName + " logged on");

  reply = fromServer.readLine();
  listArea.setText(reply);
 }

//notifies the server a client has logged off
private void logOff(String aName)throws IOException
{
 String uName = aName;
 toServer.println(uName + " logged off");
 listArea.setText("");
 toServer.println(CLIENT_LOGGINGOFF);
 closeStreams();
 socket.close();
}
}

public class Main {

 public static void main(String[] args)
 {
   ClientGUI cg = new ClientGUI("ChatClient");
   cg.setVisible(true);
 }

}

The server code is:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;

public class ServerGUI extends JFrame implements Runnable
{
 private JTextArea logArea;
 private JLabel logLabel;
 private JPanel logPanel;

 private ServerSocket ss;
 private Socket socket;

 private InputStream is;
 private OutputStream os;

 private PrintWriter toClient;
 private BufferedReader fromClient;

 static final int PORT_NUMBER = 4000;
 static final String CLIENT_LOGGINGOFF = "Exit";

 //constructor for the Server GUI
 public ServerGUI(String title)
 {
  setSize(400, 400);
  setTitle(title);
  setLocation(100, 100);
  logArea = new JTextArea(15, 30);
  JScrollPane scr = new JScrollPane(logArea);
  logLabel = new JLabel("Logging history");

  logPanel = new JPanel();
  logPanel.add(logLabel);
  logPanel.add(logArea);

  getContentPane().add(logPanel);

  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }

//constructor for the server to set the socket to handle a new thread
 public ServerGUI(Socket s)
 {
  socket = s;
 }

public void run()
{
 try
 {
  while(true)
   {

     openStreams();
     processClientRequests();
     closeStreams();
     socket.close();
   }
 }
 catch(IOException e)
     {
       System.out.println("Trouble with a connection " + e);
     }

}

//helper method for the class to set up the streams
private void open() throws IOException
{
 final boolean AUTO_FLUSH = true;
 is = socket.getInputStream();
 fromClient = new BufferedReader(new InputStreamReader(is));
 os = socket.getOutputStream();
 toClient = new PrintWriter(os, AUTO_FLUSH);
}

//process the string from received from each client
private void processRequests() throws IOException
{
 String userName;
 String reply;
 int numberOfFields = 3;
 String [] fieldContents =  new String[numberOfFields];
 userName = fromClient.readLine();
 while(!(userName.equals(CLIENT_LOGGINGOFF)))
 {
    StringTokenizer tokensIn = new StringTokenizer(userName, " ");
    int i = 0;
    while(tokensIn.hasMoreTokens())
     {
      fieldContents[i] = tokensIn.nextToken();
      i++;
     }

 reply = fieldContents[0];
 toClient.println(reply);
 logArea.append("[ " + reply + " ] "+ fieldContents[1]+"
"+fieldContents[2]+"\n");
 userName = fromClient.readLine();
 }
}

//helper method to close the streams with each client
private void close() throws IOException
{
 toClient.close();
 os.close();
 fromClient.close();
 is.close();
}
}

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

public class ChatHandler
{
static final int PORT_NUMBER = 4000;

 public ChatHandler()
 {
 }

 public void run()
 {
   try
   {
   ServerSocket server = new ServerSocket(PORT_NUMBER);
   while(true)
     {
     Socket client = server.accept ();
     System.out.println ("Accepted from " + client.getInetAddress ());
     Thread aThread = new Thread(new ServerGUI(client));
     aThread.start ();
     }
   }
   catch(IOException e)
     {
       System.out.println("Trouble with ServerSocket, port
"+PORT_NUMBER +": " + e);
     }
 }
}

public class Main {

 public static void main(String[] args)
 {
   ServerGUI sg = new ServerGUI("ChatServer");
   sg.setVisible(true);
   ChatHandler cH = new ChatHandler();
   cH.run();
 }

}

It is the first time I use threads and maybe there is something I dont
understand.  Can anyone point me to the right direction please? I think
the problem may be with the 2 server constructor but I am not sure how
to solve it.

Cheers Pat
Sean - 22 Aug 2005 11:25 GMT
On
>Hi there I was wondering if anyone can help me please.
>
[quoted text clipped - 72 lines]
>  //attempts to connect the client to the server
>  private void connectServer()

Change to connectToServer?

>  {
>   try
>    {
>     socket = new Socket(SERVER_ADDRESS, SERVER_PORT_NUMBER);
>     openStreams();

I can't find this method.  Do you mean to call open()?

>    }
>    catch(IOException e)
[quoted text clipped - 65 lines]
>  toServer.println(CLIENT_LOGGINGOFF);
>  closeStreams();

I can't find this one either.  close()?

>  socket.close();
> }
[quoted text clipped - 71 lines]
>      openStreams();
>      processClientRequests();

Is this supposed to be processRequests()?

>      closeStreams();
>      socket.close();
[quoted text clipped - 55 lines]
>import java.net.*;
>import java.io.*;

You should move your imports inside the ChatHandler class.

>public class ChatHandler
>{
> static final int PORT_NUMBER = 4000;
>
>  public ChatHandler()

This inner class shouldn't be public.

>  {
>  }
[quoted text clipped - 21 lines]
>
>public class Main {

Any particular reason you have your main method inside an inner class?  You
need to put that right in the ServerGUI class.

>  public static void main(String[] args)
>  {
[quoted text clipped - 12 lines]
>
>Cheers Pat

That's all I have for now, hope I wasn't too hard on ya.
Max010 - 22 Aug 2005 15:12 GMT
Hi Sean thanks for replying to my message and dont worry about being
hard on me.  I am a bit slow with this topic bare with me.  I ve made
some adjustment to my program and now it works but every time I run the
client and click on the connect button a new server GUI is started.
For every client GUI there is one server GUI.  I would like to have
only one server GUI that displays all the user name that logged on to
the server how do I achieve that?

thanks Pat

//start of the main class
public class Main {

 public static void main(String[] args)
 {
   HandleAClient hAc = new HandleAClient();
   hAc.run();
 }

}
//end of main class

//start of ServerGUI class
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;

public class ServerGUI extends JFrame implements Runnable
{
 private JTextArea logArea;
 private JLabel logLabel;
 private JPanel logPanel;

 private ServerSocket ss;
 private Socket socket;

 private InputStream is;
 private OutputStream os;

 private PrintWriter toClient;
 private BufferedReader fromClient;

 static final int PORT_NUMBER = 4000;
 static final String CLIENT_LOGGINGOFF = "Exit";

 public ServerGUI(String title,Socket s)
 {
  socket = s;
  setSize(400, 400);
  setTitle(title);
  setLocation(100, 100);
  logArea = new JTextArea(15, 30);
  JScrollPane scr = new JScrollPane(logArea);
  logLabel = new JLabel("Logging history");

  logPanel = new JPanel();
  logPanel.add(logLabel);
  logPanel.add(logArea);

  getContentPane().add(logPanel);

  setVisible(true);
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }

public void run()
{
 try
 {
  while(true)
   {

   openStreams();
   processClientRequests();
   closeStreams();
   socket.close();
   }
 }
 catch(IOException e)
     {
     System.out.println("Trouble with a connection "+e);
     }

}

private void openStreams() throws IOException
{
 final boolean AUTO_FLUSH = true;
 is = socket.getInputStream();
 fromClient=new BufferedReader(new                                          InputStreamReader(is));
 os = socket.getOutputStream();
 toClient = new PrintWriter(os, AUTO_FLUSH);
}

private void processClientRequests() throws IOException
{
 String userName;
 String reply;
 int numberOfFields = 3;
 String [] fieldContents =  new String[numberOfFields];
 userName = fromClient.readLine();
 while(!(userName.equals(CLIENT_LOGGINGOFF)))
 {
 StringTokenizer tokensIn =new StringTokenizer(userName,                                       "
");
    int i = 0;
    while(tokensIn.hasMoreTokens())
     {
      fieldContents[i] = tokensIn.nextToken();
      i++;
     }

 reply = fieldContents[0];
 toClient.println(reply);
 logArea.append("[ " + reply + " ] "+ fieldContents[1]+"
"+fieldContents[2]+"\n");
 userName = fromClient.readLine();
 }
}

private void closeStreams() throws IOException
{
 toClient.close();
 os.close();
 fromClient.close();
 is.close();
}
}
//end of class

//start of handle a client class
import java.io.*;
import java.net.*;

public class HandleAClient
{

 static final int PORT_NUMBER = 4000;

 public HandleAClient()
 {
 }

 public void run()
 {
  try
     {
      ServerSocket ss = new ServerSocket(PORT_NUMBER);
      while(true)
       {
        Socket client = ss.accept();
        Thread session = new Thread(new ServerGUI("chatServer4",
client));
        session.start();
       }
     }
     catch(IOException e)
     {
       System.out.println("Trouble with ServerSocket   , port
"+PORT_NUMBER +": " + e);
     }
 }
}
//end of class
Andrew Thompson - 22 Aug 2005 15:47 GMT
>  I would like to have
> only one server GUI that displays all the user name that logged on to
> the server how do I achieve that?

You might create a singleton instance of any application by
- reserving a socket and
- checking for it at start-up.

If the socket is reserved, simply bring the existing
application 'toFront()'.

HTH

Signature

Andrew Thompson
physci.org 1point1c.org javasaver.com lensescapes.com athompson.info
"As it is I'm climbing up an endless wall.  No time at all."
The Police 'No Time This Time'

Thomas Fritsch - 23 Aug 2005 00:50 GMT
> Hi there I was wondering if anyone can help me please.
>
[quoted text clipped - 8 lines]
>   at chatserverq3.ServerGUI.run(ServerGUI.java:73)
>   at java.lang.Thread.run(Thread.java:484)
You could get a lot of help from the exception stack trace above.
(*) The error occured in line 113 of ServerGUI.java in method
    processClientRequests. Exactly which line is that? Unfortunately you
did't mark
    this line in the code below. Without knowing this, I could guess, but
not help.
(*) The term "NullPointerException" tells,
    that in that line 113 an expression on the left side of a "." was null.

[...]
> //process the string from received from each client
> private void processRequests() throws IOException
[quoted text clipped - 21 lines]
>  }
> }
[...]

Signature

"TFritsch$t-online:de".replace(':','.').replace('$','@')

Max010 - 23 Aug 2005 20:47 GMT
Thanks Thomas but I ve been working on the program and now it works but
every time I launch the client frame a server frame comes up.

What I m trying to achieve is to launch several clients (no problem
with that) and only one server frame that record all the clients that
logged on and off.
Here is the server code:
//start of server class
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;

public class ServerGUI extends JFrame implements Runnable
{
 private JTextArea logArea;
 private JLabel logLabel;
 private JPanel logPanel;

 private ServerSocket ss;
 private Socket socket;

 private InputStream is;
 private OutputStream os;

 private PrintWriter toClient;
 private BufferedReader fromClient;
 private ArrayList historyUser = new ArrayList();
 static final int PORT_NUMBER = 4000;
 static final String CLIENT_LOGGINGOFF = "Exit";

//I ve created a HandleAClient class that listen for client connections
and every time that one clients request a connection it creates a
thread using the ServerGUI constructor.  Line 17 is what does that in
the HandleAClient class see below.

 public ServerGUI(String title,Socket s)
 {
  socket = s;
  setSize(400, 400);
  setTitle(title);
  setLocation(100, 100);
  logArea = new JTextArea(15, 30);
  JScrollPane scr = new JScrollPane(logArea);
  logLabel = new JLabel("Logging history");

  logPanel = new JPanel();
  logPanel.add(logLabel);
  logPanel.add(logArea);

  getContentPane().add(logPanel);

  setVisible(true);
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }

public void run()
{
 try
 {
  while(true)
   {

   openStreams();
   processClientRequests();
   closeStreams();
   socket.close();
   }
 }
 catch(IOException e)
     {
     System.out.println("Trouble with a connection "+e);
     }

}

private void openStreams() throws IOException
{
 final boolean AUTO_FLUSH = true;
 is = socket.getInputStream();
 fromClient=new BufferedReader(new                                          InputStreamReader(is));
 os = socket.getOutputStream();
 toClient = new PrintWriter(os, AUTO_FLUSH);
}

private synchronized void processClientRequests() throws IOException
{
 String userName;
 String reply;
 int numberOfFields = 3;
 String [] fieldContents =  new String[numberOfFields];

 userName = fromClient.readLine();
 while(!(userName.equals(CLIENT_LOGGINGOFF)))
 {
 StringTokenizer tokensIn =new StringTokenizer(userName,                                       "
");
    int i = 0;
    while(tokensIn.hasMoreTokens())
     {
      fieldContents[i] = tokensIn.nextToken();
      i++;
     }

 reply = fieldContents[0];
 addUserToList(reply);
 toClient.println(broadcast().toString());
 logArea.append("[ " + reply + " ] "+ fieldContents[1]+"
"+fieldContents[2]+"\n");
 userName = fromClient.readLine();
 }
}

private synchronized void addUserToList(String aUser)
{
 while(historyUser.size()>= 0)
   {
    try
       {
        wait();
       }
       catch (InterruptedException e)
       {
        String errMessage = e.getMessage();
        System.out.println("Error "+ errMessage);
       }

    historyUser.add(aUser);
    notifyAll();
    System.out.println(aUser);
   }
}

private synchronized ArrayList broadcast()
{
 ArrayList usersLogged = new ArrayList();
 Iterator listIt = historyUser.iterator();
 while(listIt.hasNext())
   {

    usersLogged.add(listIt.next());
   }

 return usersLogged;
}

private void closeStreams() throws IOException
{
 toClient.close();
 os.close();
 fromClient.close();
 is.close();
}
}
//end of server class

//start of HandleAClient class
import java.io.*;
import java.net.*;

public class HandleAClient
{

 static final int PORT_NUMBER = 4000;

 public HandleAClient()
 {
 }

 public void run()
 {
  try
     {
      ServerSocket ss = new ServerSocket(PORT_NUMBER);
      while(true)
       {
        Socket client = ss.accept();
//line 17       Thread session = new Thread(new
ServerGUI("chatServer4", client));
//unfortunately every time the ServerGUI constructor is called a new
frame appears.  How can I create a thread to handle a client without
creating a server frame???  Maybe I m doing it all wrong and there s
another strategy I could follow up any suggestion please?
        session.start();
       }
     }
     catch(IOException e)
     {
       System.out.println("Trouble with ServerSocket   , port
"+PORT_NUMBER +": " + e);
     }
 }
}

Regards Pat
Roedy Green - 30 Aug 2005 01:03 GMT
>Thanks Thomas but I ve been working on the program and now it works but
>every time I launch the client frame a server frame comes up.

Listening with one ear, it looks like you need to strip out the GUI
stuff from your server class to create an InvisibleServer, then extend
it to create a VisibleServer then spawn your extra threads as
InvisibleServers.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Again taking new Java programming contracts.



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.