简体   繁体   English

来自另一个类的Java调用方法

[英]java calling method from another class

Disclaimer - this is for an assignment, I'm trying to figure out why my code is giving me an error. 免责声明-这是一项任务,我试图弄清楚为什么我的代码给我一个错误。

Background: 背景:

So the assignment is basically to make edits to SimpleChat, a client-server framework for which the teacher has given us the code. 因此,作业基本上是对SimpleChat进行编辑,SimpleChat是一个客户端-服务器框架,教师已为我们提供了代码。 I am trying to implement a chat console from the server side, and implement actions that begin with hashtags. 我正在尝试从服务器端实现聊天控制台,并实现以#标签开头的操作。 So I have a "handleMessageFromServer" method in my server file (called "EchoServer"), and am trying to call it from the server console (aptly named "Server Console"). 因此,我在服务器文件(称为“ EchoServer”)中有一个“ handleMessageFromServer”方法,并试图从服务器控制台(恰当地命名为“服务器控制台”)中调用它。 I'll put the relevant code below, and explain it: 我将相关代码放在下面,并进行解释:

I'll edit what I've put, I'll put the whole files with comments. 我将编辑所放内容,并在整个文件中添加注释。

Below is the "EchoServer" file. 下面是“ EchoServer”文件。 The more important bits relevant to my question are the "handleMessageFromServer" method, which I am trying to call from the other file and pass in information, as well as the EchoServer constructor, which I am using in the other file to create an instance. 与我的问题相关的更重要的部分是“ 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

Below is the ServerConsole file, where I am creating an instance of the EchoServer class so that I may pass in information. 下面是ServerConsole文件,我在其中创建EchoServer类的实例,以便我可以传递信息。 The purpose of this file is to create an environment where the server side can send text for the SimpleChat application. 该文件的目的是创建一个服务器端可以为SimpleChat应用程序发送文本的环境。 The text then gets passed back to the EchoServer class, where it can be used for commands (all the commands begin with hashtags). 然后,该文本将传递回EchoServer类,该类可用于命令(所有命令均以井号开头)。 I am currently getting an error in the "accept" method, when trying to call echoServer.handleMessageFromServer(message). 尝试调用echoServer.handleMessageFromServer(message)时,当前在“ accept”方法中出现错误。 The error is "The method handleMessageFromServer(String) is undefined for the type EchoServer". 错误是“类型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

I think I might not be constructing the instance right, but any help is greatly appreciated guys! 我想我可能没有正确构造实例,但是对大家的帮助非常感谢!

Your echoserver class has the following contructor: 您的echoserver类具有以下构造函数:

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

note it takes in two parameters. 注意它有两个参数。

your call to the EchoServer is however only injecting a port 您对EchoServer的呼叫只是注入一个端口

this.echoServer = new EchoServer(port);

Without seeing all your code my guess would be that Echoserver extends some other Server class that does not have the method you want. 如果没有看到您所有的代码,我的猜测是Echoserver扩展了其他一些没有所需方法的Server类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM