Try to share a socket with an object in the parent class

advertisements

can anyone enlighten me? I was trying to access a socket in an object belonging to a parent class (main applet class). I wish I could make this more consise for you. Bit of a mouthful but maybe my source will explain a little further.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JApplet;
import javax.swing.JOptionPane;

class SocketsC {

    Socket clientsocket;
    static PrintWriter out;
    static BufferedReader in;

    public void SocketsC()  {

    }

    public void connectSock()   {

        try {

            clientsocket = new Socket( "localhost", 9900 );
            out = new PrintWriter(clientsocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader( clientsocket.getInputStream()));

        } catch (UnknownHostException e) {

            System.exit(1);

        } catch (IOException e) {

            System.exit(1);
        }
    }
}

class AccessSock    {

  AccessSock()  {

        // Here is where I am trying to access the socket from the mysocks object
      mysocks.out.println( "working" );  // This doesn't work...
  }

}

public class main extends JApplet {

    static SocketsC mysocks;

    public void init() {

      createApp();
    }

    public void createApp() {

        SocketsC mysocks = new SocketsC();
        AccessSock sendtext = new AccessSock();
    }
}

TYIA -Roland


Since you have defined mysocks as static, you need to use className.variable to access it.

static SocketsC mysocks;

Change this:

mysocks.out.println( "working" );

to

main.mysocks.out.println( "working" );

This should work. Since there is no variable called mysocks in your class. It is throwing error.