2016-07-05 2 views
0

나는이 튜토리얼을 따라 다중 클라이언트와 하나의 서버와 채팅을했다 : http://inetjava.sourceforge.net/lectures/part1_sockets/InetJava-1.9-Chat-Client-Server-Example.html 하지만 문제가있다. 클라이언트가 명령 프롬프트를 통해 앱을 시작할 때 클라이언트가 사용자 이름을 보내길 원한다. : java -jar Client.jar Jonny 하지만 어떻게해야할지 모르겠다. 누군가 나를 설명 할 수 있다면 .. 답해 주셔서 감사합니다.자바 채팅 서버 클라이언트 문제

답변

1

java -jar Client.jar Jonny과 같은 매개 변수를 입력하면 Client 클래스의 main 메소드에서 인수를 문자열 배열로 가져올 수 있습니다.

예를 들어, 당신은 다음과 같이 첫 번째 인수를 인쇄 할 수 있습니다 :

public static void main(String[] args) 
{ 
    //This will output: "The first argument is: Jonny" 
    System.out.println("The first argument is: "+args[0]); 
} 

당신이 지금해야 할 모든 서버에이를 보낼 수 있습니다. NakovChat 예제를 사용하면 다음과 같이 될 수 있습니다.

public static void main(String[] args) 
    { 
     BufferedReader in = null; 
     PrintWriter out = null; 
     try { 
      // Connect to Nakov Chat Server 
      Socket socket = new Socket(SERVER_HOSTNAME, SERVER_PORT); 
      in = new BufferedReader(
       new InputStreamReader(socket.getInputStream())); 
      out = new PrintWriter(
       new OutputStreamWriter(socket.getOutputStream())); 

      System.out.println("Connected to server " + 
       SERVER_HOSTNAME + ":" + SERVER_PORT); 
      //We print out the first argument on the socket's outputstream and then flush it 
      out.println(args[0]); 
      out.flush(); 
     } catch (IOException ioe) { 
      System.err.println("Can not establish connection to " + 
       SERVER_HOSTNAME + ":" + SERVER_PORT); 
      ioe.printStackTrace(); 
      System.exit(-1); 
     } 

     // Create and start Sender thread 
     Sender sender = new Sender(out); 
     sender.setDaemon(true); 
     sender.start(); 


     try { 
      // Read messages from the server and print them 
      String message; 
      while ((message=in.readLine()) != null) { 
       System.out.println(message); 
      } 
     } catch (IOException ioe) { 
      System.err.println("Connection to server broken."); 
      ioe.printStackTrace(); 
     } 

    } 
}