-1

I'm trying to connect to a socket and then check if it is connected. My problem is that my socket IS connecting but when I ask if it is, it returns null.

How I'm getting my connection:

package main;

import java.io.IOException;
import java.net.Socket;

public class getIrcConnection {

    String Server = "tmi.twitch.tv";
    int Port = 80;

    declars declars = new declars();

    public getIrcConnection() throws IOException{

    this.declars.socket = new Socket(Server, Port);

    }

}

Where my socket is stored:

package main;

import java.net.Socket;

public class declars {

    Socket socket;

}

How I'm checking the connection:

package main;


public class checkIrcConnection {

    declars declars = new declars();

    public checkIrcConnection() {

        if (this.declars.socket.isConnected()) {           
        System.out.println("Connected");     
        }

      }

}

All of this is beeing executed in the main method:

package main;

public class Main {

    public static void main(String[] args) throws Exception {

        getIrcConnection gic = new getIrcConnection();

        checkIrcConnection cic = new checkIrcConnection();

    }

}
TomiG
  • 17
  • 5
  • 1
    It appears you are implementing what should be ordinary functions as classes and putting the implementation in the constructor. That's a bit unusual. – selbie Dec 09 '16 at 18:28
  • `Socket` is *not* 'returning null'. Your *code* is *throwing* `NullPointerException` when it calls `Socket.isConnected()`, obviously on a null `Socket` variable. If you had observed the error properly and not misdescribed it to yourself you wouldn't have had to post the question. – user207421 Dec 09 '16 at 18:34

2 Answers2

1

You have two declars objects. One you setting gic.declars and the other you are using cic.declars. I.e. you are using the one you didn't set.

I suggest you step through the code in your debugger as you have a simple confusion which should be obvious from a debugger.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

First of all organize your code in an Object Oriented way. Consider classes as objects and these objects must have common attributes and common operations. Than distribute all the functionality to the objects. If you would do that, it would be much easier to debug and understand the error.

If you want to do some http request to an URL, and process the returning result, it would be nice to use some libraries around. For example you can use unirest

Or if you want to exercise the socket programming in java, you can refer to java tutorial about sockets

mndeveci
  • 301
  • 4
  • 15