尝试与父类中的对象共享套接字

时间:2013-02-25 04:05:11

标签: java oop sockets applet

任何人都可以开导我吗?我试图访问属于父类(主applet类)的对象中的套接字。我希望我能为你更加明智。有点满口但可能是我的来源会进一步解释。

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

3 个答案:

答案 0 :(得分:1)

由于您已将mysocks定义为静态,因此您需要使用className.variable来访问它。

static SocketsC mysocks;

改变这个:

mysocks.out.println( "working" );

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

这应该有效。由于您的班级中没有名为mysocks的变量。这是投掷错误。

答案 1 :(得分:0)

从您的代码mysocks.out.println( "working" );我知道您想要访问println方法
所以你可以使用

直接做到这一点
SocketsC.out.println( "working" );

答案 2 :(得分:0)

试试......

 public class main extends JApplet {
    //existing code

    public void createApp() {
      mysocks = new SocketsC();
      AccessSock sendtext = new AccessSock(mysocks);
  }

class AccessSock    {

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

  }
}