0

免责声明 - 这是一个作业,我试图弄清楚为什么我的代码给了我一个错误。

背景:

所以任务基本上是对 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) 时,我目前在“接受”方法中遇到错误。错误是“未为类型 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

我想我可能没有正确构建实例,但是非常感谢任何帮助!

4

1 回答 1

1

您的 echoserver 类具有以下构造函数:

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

注意它有两个参数。

但是,您对 EchoServer 的调用只是注入了一个端口

this.echoServer = new EchoServer(port);

如果没有看到您的所有代码,我的猜测是 Echoserver 扩展了其他一些没有您想要的方法的 Server 类。

于 2013-10-01T03:52:42.753 回答