簡體   English   中英

來自另一個類的Java調用方法

[英]java calling method from another class

免責聲明-這是一項任務,我試圖弄清楚為什么我的代碼給我一個錯誤。

背景:

因此,作業基本上是對SimpleChat進行編輯,SimpleChat是一個客戶端-服務器框架,教師已為我們提供了代碼。 我正在嘗試從服務器端實現聊天控制台,並實現以#標簽開頭的操作。 因此,我在服務器文件(稱為“ EchoServer”)中有一個“ handleMessageFromServer”方法,並試圖從服務器控制台(恰當地命名為“服務器控制台”)中調用它。 我將相關代碼放在下面,並進行解釋:

我將編輯所放內容,並在整個文件中添加注釋。

下面是“ EchoServer”文件。 與我的問題相關的更重要的部分是“ handleMessageFromServer”方法(我正在嘗試從另一個文件中調用並傳遞信息),以及EchoServer構造函數(在另一個文件中用於創建實例)。

import java.io.*;
import ocsf.server.*;
import common.*;

/**
 * This class overrides some of the methods in the abstract 
 * superclass in order to give more functionality to the server.
 *
 * @author Dr Timothy C. Lethbridge
 * @author Dr Robert Laganière
 * @author François Bélanger
 * @author Paul Holden
 * @version July 2000
 */
public class EchoServer extends AbstractServer 
{
  //Class variables *************************************************

  /**
   * The default port to listen on.
   */
  final public static int DEFAULT_PORT = 5555;

  //Constructors ****************************************************

  /*
   * An interface type variable, will allow the implementation of the 
   * Display method in the client.
   * 
   */
  public ChatIF server;
  /**
   * Constructs an instance of the echo server.
   *
   * @param port The port number to connect on.
   */
  public EchoServer(int port, ChatIF server)
  {
      super(port);
      this.server = server;
  }

  //Instance methods ************************************************

  /**
   * This method handles any messages received from the client.
   *
   * @param msg The message received from the client.
   * @param client The connection from which the message originated.
   */
  public void handleMessageFromClient
    (Object msg, ConnectionToClient client)
  {
    System.out.println("Message received: " + msg + " from " + client);
    this.sendToAllClients(msg);
  }

  /**
   * This method handles any messages received from the server console.
   *
   * @param msg The message received from the server.
   * @param server The connection from which the message originated.
   */
  public void handleMessageFromServer(String message)
  {
    if (message.charAt(0) == '#')
    {
      serverCommand(message);
    }
    else
    {
      server.display(message);
      this.sendToAllClients("SERVER MSG> " + message);
    }
  }
  /*This method allows us to run commands from the server console
   * 
   */
  public void serverCommand(String command)
  {
      if (command.equalsIgnoreCase("quit")) System.exit(0);      /////Shuts the system down
      else if (command.equalsIgnoreCase("#stop")) stopListening();  ///Stops listening for connections
      else if (command.equalsIgnoreCase("#close"))            ///////closes all connections
      {
          try close();
                  catch(IOException ex) {
                      server.display("Could not close connection");
                  }
      }
      else if (command.toLowerCase().startsWith("#setport"))           /////Sets port when not listening
      {
        if (!isListening() && getNumberOfClients() == 0)
        {
            //////If there are no connected clients, and
            //////we're not listening for new ones, we can 
            ////assume that the server is closed (close() has been 
            ////called. 
            String portNum = command.substring(s.indexOf("<") + 1)
            portNum = portnum.substring(0, s.indexOf(">"));
            int num = Integer.parseInt(portNum);
            setPort(num);
            server.display("The server port has been changed to port" + getPort());
        }
        else
        {
            server.display("Port cannot be changed");
        }
        else if (command.equalsIgnoreCase("#start"))     ///////starts listening for clients if not already
        {
            if (!isListening())
            {
                try listen();
                catch (Exception ex)
                {
                    server.display("Could not listen for clients!");
                }
            }
            else
            {
                server.display("Already listening for clients");
            }
        }
        else if (message.equalsIgnoreCase("#getport"))    //////gets the port number
        {
            server.display("Current port: " + Integer.toString(getPort()));
        }
      }
  }

  /**
   * This method overrides the one in the superclass.  Called
   * when the server starts listening for connections.
   */
  protected void serverStarted()
  {
    System.out.println
      ("Server listening for connections on port " + getPort());
  }

  /**
   * This method overrides the one in the superclass.  Called
   * when the server stops listening for connections.
   */
  protected void serverStopped()
  {
    System.out.println
      ("Server has stopped listening for connections.");
  }

  //Class methods ***************************************************

  /**
   * This method is responsible for the creation of 
   * the server instance (there is no UI in this phase).
   *
   * @param args[0] The port number to listen on.  Defaults to 5555 
   *          if no argument is entered.
   */
  public static void main(String[] args) 
  {
    int port = 0; //Port to listen on

    try
    {
      port = Integer.parseInt(args[0]); //Get port from command line
    }
    catch(Throwable t)
    {
      port = DEFAULT_PORT; //Set port to 5555
    }

    EchoServer sv = new EchoServer(port);

    try 
    {
      sv.listen(); //Start listening for connections
    } 
    catch (Exception ex) 
    {
      System.out.println("ERROR - Could not listen for clients!");
    }
  }
}
//End of EchoServer class

下面是ServerConsole文件,我在其中創建EchoServer類的實例,以便我可以傳遞信息。 該文件的目的是創建一個服務器端可以為SimpleChat應用程序發送文本的環境。 然后,該文本將傳遞回EchoServer類,該類可用於命令(所有命令均以井號開頭)。 嘗試調用echoServer.handleMessageFromServer(message)時,當前在“ accept”方法中出現錯誤。 錯誤是“類型EchoServer的方法handleMessageFromServer(String)未定義”。

import java.io.*;
import client.*;
import common.*;

/**
 * This class constructs the UI for a chat client.  It implements the
 * chat interface in order to activate the display() method.
 * Warning: Some of the code here is cloned in ServerConsole 
 *
 * @author Fran&ccedil;ois B&eacute;langer
 * @author Dr Timothy C. Lethbridge  
 * @author Dr Robert Lagani&egrave;re
 * @version July 2000
 */
public class ServerConsole implements ChatIF 
{
  //Class variables *************************************************

  /**
   * The default port to connect on.
   */
  final public static int DEFAULT_PORT = 5555;

  //Instance variables **********************************************

  /**
   * The instance of the server that created this ConsoleChat.
   */
  //Constructors ****************************************************
  EchoServer echoServer;
  /**
   * Constructs an instance of the ClientConsole UI.
   *
   * @param host The host to connect to.
   * @param port The port to connect on.
   */
  public ServerConsole(int port) 
  {
   this.echoServer = new EchoServer(port);
  } 

  //Instance methods ************************************************

  /**
   * This method waits for input from the console.  Once it is 
   * received, it sends it to the client's message handler.
   */
  public void accept() 
  {
    try
    {
      BufferedReader fromConsole = 
        new BufferedReader(new InputStreamReader(System.in));
      String message;

      while (true) 
      {
        message = fromConsole.readLine();
        ///////////////ADDED FOR E50B       MA/ND
        echoServer.handleMessageFromServer(message);
        ///////////////ADDED FOR E50B       MA/ND
      }
    } 
    catch (Exception ex) 
    {
      System.out.println
        ("Unexpected error while reading from console!");
    }
  }

  /**
   * This method overrides the method in the ChatIF interface.  It
   * displays a message onto the screen.
   *
   * @param message The string to be displayed.
   */
  public void display(String message) 
  {
                 System.out.println(message);
  }


  //Class methods ***************************************************

  /**
   * This method is responsible for the creation of the Client UI.
   *
   * @param args[0] The host to connect to.
   */
  public static void main(String[] args) 
  {
    int port = 0;  //The port number

    try
    {
      String host = args[0];
    }
    catch(ArrayIndexOutOfBoundsException e)
    {
     String host = "localhost";
    }
    ServerConsole chat= new ServerConsole(DEFAULT_PORT);
    chat.accept();  //Wait for console data
  }
}
//End of ConsoleChat class

我想我可能沒有正確構造實例,但是對大家的幫助非常感謝!

您的echoserver類具有以下構造函數:

public EchoServer(int port, ChatIF server)
  {
      super(port);
      this.server = server;
  }

注意它有兩個參數。

您對EchoServer的呼叫只是注入一個端口

this.echoServer = new EchoServer(port);

如果沒有看到您所有的代碼,我的猜測是Echoserver擴展了其他一些沒有所需方法的Server類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM