0

谁能启发我?我试图访问属于父类(主小程序类)的对象中的套接字。我希望我能为你做这个更简洁。有点拗口,但也许我的消息来源会进一步解释。

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-罗兰

4

3 回答 3

1

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

static SocketsC mysocks;

改变这个:

mysocks.out.println( "working" );

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

这应该有效。mysocks由于您的类中没有调用变量。它正在抛出错误。

于 2013-02-25T04:12:08.217 回答
0

从您的代码mysocks.out.println( "working" );中,我了解到您想要访问println方法
所以您可以直接使用

SocketsC.out.println( "working" );
于 2013-02-25T04:19:43.210 回答
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...

  }
}
于 2013-02-25T04:21:12.300 回答