0

I'm trying to write a basic chat server which will forward messages from one client to another.

I have my client running on another laptop and the server gets the user name which I send so surely the ObjectInputStream isn't null and the user name isn't null?

Here is the HashMap and ObjectInputStream:

private Socket[] clientSocket = new Socket[100];
private ObjectInputStream[] fromClient = new ObjectInputStream[100];
private ObjectOutputStream[] toClient = new ObjectOutputStream[100];
private HashMap<String, ObjectInputStream> clientInputs= new HashMap<String, ObjectInputStream>();
private HashMap<String, ObjectOutputStream> clientOutputs= new HashMap<String, ObjectOutputStream>();;

Here's the bit where I get the null pointer exception:

//This is just for testing:
System.out.println("User name is :" +userName);
System.out.println("fromClient[i] is " +fromClient[i].toString());
Thread.sleep(1000);

//Add this user to all lists.
clientInputs.put(userName , (ObjectInputStream)fromClient[i]);*
clientOutputs.put(userName, (ObjectOutputStream)toClient[i]);
onlineUsers[i] = userName;

I get: [Line 105 is the line clientInputs.put(...,...); where I marked with a *.]

    User name is :hulo
    fromClient[i] is java.io.ObjectInputStream@147c5fc
    Exception in thread "Thread-0" java.lang.NullPointerException
        at AcceptConnections.addNextUser(AcceptConnections.java:105)
        at AcceptConnections.run(AcceptConnections.java:53)

I don't know if this has anything to do with it but without the line Thread.sleep(1000); the NullPointerException comes out after the "user name is" line but before the "fromClient[i]" line.

Edit: I'm not sure if I made it clear, but these lines of code are after my client program has connected to the server so the user name is the one taken from the client during a test run and so the ObjectInputStream is definitely working.

jordanhill123
  • 4,142
  • 2
  • 31
  • 40
Calum
  • 27
  • 7

1 Answers1

0

It looks like you're not initializing clientInputs.

Maybe change your declaration to:

private HashMap clientInputs= new HashMap();

Andrew Stubbs
  • 4,322
  • 3
  • 29
  • 48
  • 1
    Questions should be in comments, not answers. Answers are here to answer to a question. – Kabulan0lak Jul 10 '14 at 11:48
  • Turns out it was the problem. Somewhere else in the code I was setting it back to be un-initialized. Thanks :) – Calum Jul 10 '14 at 12:06