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.