0

I have a problem in returning an instance of an object which is defined inside a class, in the code below I tried to make a Socket connection inside of a class which extends Thread . the socket_connect class:

public class socket_connect extends Thread {
    private Socket socket;
    private OutputStream out;
    private String host;
    private int port;
    socket_connect(String host,int port){
        this.host=host;
        this.port=port;
        this.start();
    }
    @Override
    public void run() {
        try {
            this.socket = new Socket(this.host,this.port);
            this.out=new BufferedOutputStream(this.socket.getOutputStream());
            this.out.write("i am here \n\r".getBytes());
            this.out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public int getPort() {
        return port;
    }
    public String getHost() {
        return host;
    }
    public Socket getSocket() {
              return socket;
    }
    public  OutputStream getOut() {
        return out;
    }
}

the main class:

public class mymain {
public static void main(String[] args) {
    Socket backsock;
    String backhost;
    int backport;
    String msg ="Second Hi!!!!!";
    socket_connect sc = new socket_connect("127.0.0.1",8080);
    backsock = sc.getSocket();
    backhost = sc.getHost();
    backport = sc.getPort();
    System.out.println(backhost + " " + backport);
    try {
        OutputStream buffer= new BufferedOutputStream(backsock.getOutputStream());
        buffer.write(msg.getBytes());
        buffer.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
    while (true) { }
}

}

The connection is established and Outputstream inside the Socket_connect class will write "I am here !!!" to the server . but when i try to execute another write procces with New Outputstream defined inside main i get an error in the line OutputStream buffer= new BufferedOutputStream(backsock.getOutputStream()); it seems that the backsocket which i defined inside the main file is null . even though i used backsock = sc.getSocket(); to make it the same socket i defined inside the instance sc . however gethost() and getPort() works perfectly :

backhost = sc.getHost();
backport = sc.getPort();
System.out.println(backhost + " " + backport);

this will print the 127.0.0.1 8080 I can get them back and store them inside int and string defined in main and use System.out to print them but I can't get back the Socket or outputstream from class. they return null. I used to use C++ and there was a pointer to point at the exact object in a program , but here I can't.

3
  • Unrelated: read about java naming conventions. Class names go UpperCamelCase in java, always. And you dont use "_" in names, unless for SOME_CONSTANT. Commented Oct 15, 2019 at 7:09
  • And just for the record: what you are doing there is almost non-sensical. Besides adding ways to not work, using threads here ... really doesnt do anything meaningful. If you want to learn about multi threading: read a good book or tutorial, and follow that. Dont try to invent your own use cases, when your knowledge isnt ready for that. Commented Oct 15, 2019 at 7:11
  • @ghostcat i am trying to work java in android , dosent let me use write in main thread , so i have to make 3 threads one for connect two for write and three for read but i need the socket to be the same for all three threads Commented Oct 15, 2019 at 8:08

2 Answers 2

1

Try run this program several time you may find it working, for some cases. It seems that it is a thread related issue. When you are executing, main method may continue execution even before the socket_connect thread start executing run() method. get method of host and port works because values are already assigned outside of run() method. You can simple check it by waiting for few moments into main method using Thread.sleep(). Example:

...
int backport;
String msg ="Second Hi!!!!!";
socket_connect sc = new socket_connect("127.0.0.1",8080);
// add try catch or throw 
// by this time hopefully the socket_connect will start.
Thread.sleep(1000);
backsock = sc.getSocket();
backhost = sc.getHost();
backport = sc.getPort();
System.out.println(backhost + " " + backport);

Note: also waiting indefinitely while(true) is not a good practice. All you can do is to try read something from sockets input stream.

Sign up to request clarification or add additional context in comments.

1 Comment

YES YES YES , thank you , i needed to make the main thread sleep , it seems i needed a delay to make the time for connection to be connected then get the output in the main Thread
1

The problem is you try to get Socket before it get created. you should integrate thread synchronization technique into your code something like this.

public class socket_connect extends Thread {
    private Socket socket;
    private OutputStream out;
    private String host;
    private int port;
    private Semaphore sema = new Semaphore(1);

    socket_connect(String host, int port) {
        try {
            this.host = host;
            this.port = port;
            this.sema.acquire();
            this.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            this.socket = new Socket(this.host, this.port);
            this.out = new BufferedOutputStream(this.socket.getOutputStream());
            this.out.write("i am here \n\r".getBytes());
            this.out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            sema.release();
        }
    }

    public int getPort() throws InterruptedException {
            return port;
    }

    public String getHost() {
        return host;
    }

    public Socket getSocket() throws InterruptedException {
        try {
            sema.acquire();
            return socket;
        } finally {
            sema.release();
        }
    }

    public OutputStream getOut() throws InterruptedException {
        try {
            sema.acquire();
            return out;
        }finally {
            sema.release();
        }
    }

public static void main(String[] args) throws InterruptedException {
            Socket backsock;
            String backhost;
            int backport;
            String msg = "Second Hi!!!!!";
            socket_connect sc = new socket_connect("google.com", 80);
            backsock = sc.getSocket();
            backhost = sc.getHost();
            backport = sc.getPort();
            System.out.println(backhost + " " + backport);
            try {
                OutputStream buffer = new BufferedOutputStream(backsock.getOutputStream());
                buffer.write(msg.getBytes());
                buffer.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
}

1 Comment

dorod . merci hadi jan , felan ba gozahstane ye delay toye main moshkelo hal kardam , in chizi ke shoma neveshtiym bayad test konam

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.