gpt4 book ai didi

java从另一个类调用方法

转载 作者:行者123 更新时间:2023-12-01 14:03:46 25 4
gpt4 key购买 nike

免责声明 - 这是一项作业,我试图找出为什么我的代码给我一个错误。

背景:

所以作业基本上是对 SimpleChat 进行编辑,这是一个客户端-服务器框架,老师已经给了我们代码。我正在尝试从服务器端实现聊天控制台,并实现以主题标签开头的操作。因此,我的服务器文件中有一个“handleMessageFromServer”方法(称为“EchoServer”),并尝试从服务器控制台(恰本地命名为“服务器控制台”)调用它。我将相关代码放在下面,并解释一下:

我将编辑我所放置的内容,我将在整个文件中添加注释。

下面是“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 的调用只是注入(inject)一个端口

this.echoServer = new EchoServer(port);

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

关于java从另一个类调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19107574/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com