2013-10-01 3 views
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)를 호출하려고 할 때 현재 "accept"메서드에서 오류가 발생합니다. 오류는 "handleMessageFromServer (String) 유형이 EchoServer 유형에 대해 정의되지 않았습니다."입니다.

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 

저는 인스턴스를 올바르게 구성하지 못했을 것이라고 생각합니다. 그러나 도움은 대단히 감사합니다! 이 두 개의 매개 변수에 소요

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

참고 :

+0

무엇이 오류 메시지입니까? – nhgrif

+0

을 조각으로 분할하는 대신 게시를 편집하고 해당 클래스에 메서드를 넣고 필요한 경우 언제든지 주석을 넣을 수 있습니다. – Arham

+0

필드의 범위를 확인하십시오. 두 개의 다른 '호스트'를 선언했기 때문에 try catch 블록에서 오류가 발생했습니다. 마지막 상자의 두 부분이 어디 있는지 확인하는 데 도움이됩니다. – clwhisk

답변

1

귀하의 echoserver 클래스는 다음과 같은 생성자가 있습니다.

EchoServer에 전화 그러나 단지 내 추측이 Echoserver 원하는 방법이없는 다른 서버 클래스를 확장하는 것 모든 코드를 보지 않고 포트

this.echoServer = new EchoServer(port); 

를 주입한다.

+0

그것은 참조 용으로 "AbstractServer"라는 다른 서버 파일을 확장합니다. 그러나 EchoServer 파일에이 메서드를 넣었고 EchoServer를 통해 호출 할 수 없으면 AbstractServer 파일에서 상속하는 다른 자식 클래스가 없습니다. –

관련 문제