0

hey im having problems with java messenger application. i've made a simple gui in netbeans and a server and client class. when i create a new instance of server in gui i start a new thread and start listening in it. the problem occurs when server gets something and goes to handleConnection() where i want to use setText() on a JTextPane in another class and another thread(GUI). here's the code:

code for connect button in gui's class:

private void doConnect(java.awt.event.ActionEvent evt) {                           

        server = new mServer(1234);
        ms = new mServer(this);
        Thread t = new Thread(server);
        t.start();
        statusLine.setText("Connection established");
    }  

server class:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nejc;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;

/**
 *
 * @author Nejc
 */
public class mServer implements Runnable{

    private int port;

    JMessenger jMsg;

    public mServer(int port){

    this.port=port;
    }

    public mServer(JMessenger in){

        jMsg = in;
    }

    public void listen(){

        try{

            ServerSocket listener = new ServerSocket(port);
            Socket server;

            while(true){

                server = listener.accept();
        handleConnection(server);
            }

        }
    catch (IOException ioe){

            System.out.println("IOException: " + ioe);
            //ioe.printStackTrace();
            System.exit(1);
    }
    }

    protected void handleConnection(Socket server) throws IOException{

        //DataOutputStream out = new DataOutputStream(server.getOutputStream());
    final DataInputStream in = new DataInputStream(server.getInputStream());

        Runnable r = new Runnable(){

            @Override
            public void run(){

                try{

                    jMsg.field.setText("Mitja: " + in.readUTF());
                }
                catch (IOException ex){

                    Logger.getLogger(mServer.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        };
        SwingUtilities.invokeLater(r);


    //out.writeUTF(output);

        /*JTextPane field = jMsg.field;
        String mssg = in.readUTF();
        field.setText(mssg);
        * 
        */

    server.setKeepAlive(true);
    }

    @Override
    public void run(){

        listen();
    }
}

Sorry I forgot about that:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at com.nejc.mServer$1.run(mServer.java:70)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:705)
    at java.awt.EventQueue.access$000(EventQueue.java:101)
    at java.awt.EventQueue$3.run(EventQueue.java:666)
    at java.awt.EventQueue$3.run(EventQueue.java:664)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:675)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
tenorsax
  • 21,123
  • 9
  • 60
  • 107
inejc
  • 550
  • 3
  • 14

3 Answers3

3

What I see as a dangerous idea is to read from the socket input stream inside the Runnable that you are sending off to the Event Dispatch Thread. Read the input stream immediately in handleConnection and pass the String to the runnable:

protected void handleConnection(Socket server) throws IOException{
  final String s = new DataInputStream(server.getInputStream()).readUTF();
  SwingUtilities.invokeLater(new Runnable(){ public void run() {
    jMsg.field.setText("Mitja: " + s);
  }});
}
Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • It's a good suggestion, but it still wouldn't resolve the exception he is probably seeing. – SimonC May 13 '12 at 10:35
  • 2
    Should I repeat your advice in my answer? I think it's fair that I leave that part to you. Now let's remove each other's downvotes and shake hands. – Marko Topolnik May 13 '12 at 10:35
  • +1, I liked this idea, about getting the input and passing the value to the EDT :-) – nIcE cOw May 13 '12 at 10:36
  • @nIcE cOw in all cases you can to avoiding to put try - catch - finally block inside invokeLater() – mKorbel May 13 '12 at 11:37
  • @mKorbel Yes, the try-catch should stay with readUTF() now, if anywhere. The method is already declaring `IOException`. – Marko Topolnik May 13 '12 at 11:39
  • @mKorbel : Ahha, didn't knew about this complexity of `try-catch` block, Thankyou for sharing this info, I got a picture now, as to what might can happen, if an exception came by, which is not related to the View of the Application, nice thingy, never thought of that, in that detail :-) – nIcE cOw May 13 '12 at 12:01
3

You're creating two instances of mServer, server and ms. server's jMsg is null so I expect you're getting a NullPointerException in the run method.

UPDATE

Take note of Marko's answer about not reading from the input stream on the GUI thread.

SimonC
  • 6,590
  • 1
  • 23
  • 40
  • `server` is not `null`: `server = listener.accept(); handleConnection(server);` – Marko Topolnik May 13 '12 at 10:20
  • 1
    I said that the variable `jMsg` is `null` in the `server` instance. There should probably be one instance of `mServer` who's constructor takes both a port and `JMessenger`. – SimonC May 13 '12 at 10:23
  • OP: "the problem occurs when server gets something and goes to handleConnection()" – Marko Topolnik May 13 '12 at 10:24
  • Right, `handleConnection` creates an anonymous instance of `Runnable` that has a `run` method that tries to dereference `jMsg` which will be `null`, thus I expect a `NullPointerException` is getting thrown. – SimonC May 13 '12 at 10:26
  • Boy, that's confused code. When he solves that, he'll be having more problems down the road. But anyway, he didn't respond to requests to add the exc stacktrace, so why bother anymore, really. – Marko Topolnik May 13 '12 at 10:29
  • Sorry, my vote is locked in since you didn't edit the post. Edit and I'll fix that. – Marko Topolnik May 13 '12 at 10:37
  • I doubt, what you being pointing to in your answer as the right answer, since the OP said just a problem, he/she never said about any Exceptions, though if you look at the constructor of the `mServer` you will see that `jMsg` is pointing to something, though is that value `null or not` is something we can not tell, without looking into the actual code (as to which constructor is being called for). +1 though for the info :-) – nIcE cOw May 13 '12 at 10:39
  • @nIcEcOw, we do have that code, it's in the `doConnect` method in the first code snippet. – SimonC May 13 '12 at 10:42
  • Ahha, true, I missed that part, LOL, seems like OP needs to learn some basics related to making objects and passing values, My BAD :-) – nIcE cOw May 13 '12 at 10:44
0

I wanted to comment on one of the other answers but I couldn't figure out how to do that. Its not so much an answer of its own but I think its worth mentioning, DataInputStream is deprecated from what I understand because of issues with Strings and characters. being that a large part of a messaging application rely on strings and characters you may want to try using a BufferedReader instead.

 BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

Hope that helped a little, sorry if I commented in the wrong place. I'm still getting used to this site's etiquette,

Kevin Bigler
  • 256
  • 1
  • 2
  • 9