2012-01-28 3 views
0

여러 클라이언트를 허용하는 TCP 채트 서버를 만드는 방법에 대해 알아 본 자습서를 수정합니다. 결국 클라이언트 클래스도 만들지 만, 지금까지는 TELNET으로 테스트하고 있습니다.TCP 채팅 서버

서버에서 입력을 계속 확인하므로 서버 기능을 수행하기 위해 키워드를 사용할 수 있습니다. 따라서 "OK"를 인쇄하려면 클라이언트와 문자열 "Name :"을 연결 해제하려면 "EXIT"를 입력하십시오.

내가 생각하지만 그것은 작동하지 않는 것입니다 : 모른 채

public void run() 
    { 
     String line; 
     try  
     { 
      while(true) 
      { 
       if (input.readline("EXIT"))//Should close and remove client 
       { 
        clients.remove(this); 
        users.remove(name); 
        break; 
       } 
       if(input.readline("Name:"))//Should print OK with username 
       { 
        System.out.println("OK"); 
       } 
       boradcast(name,line); // method of outer class - send messages to all 
      }// end of while 
     } // try 
     catch(Exception e) 
     { 
      System.out.println(e.getMessage()); 
     } 
    } // end of run() 
} 

} 여기

전체 서버 클래스

// Chat Server runs at port no. 9020 
import java.io.*; 
import java.util.*; 
import java.net.*; 
import static java.lang.System.out; 

public class TCPServer 
{ 
    Vector<String> users = new Vector<String>(); 
    Vector<HandleClient> clients = new Vector<HandleClient>(); 

    int PORT = 9020; 
    int NumClients = 10; 

    public void process() throws Exception 
    { 
     ServerSocket server = new ServerSocket(PORT,NumClients); 
     out.println("Server Connected..."); 
     while(true) 
     { 
     Socket client = server.accept(); 
     HandleClient c = new HandleClient(client); 
     clients.add(c); 
    } // end of while 
    } 

    public static void main(String ... args) throws Exception 
    { 
     new TCPServer().process(); 
    } // end of main 

    public void boradcast(String user, String message) 
    { 
     // send message to all connected users 
     for (HandleClient c : clients) 
      if (!c.getUserName().equals(user)) 
      { 
       c.sendMessage(user,message); 
      } 
    } 

    class HandleClient extends Thread 
    { 
    String name = ""; 
    BufferedReader input; 
    PrintWriter output; 

    public HandleClient(Socket client) throws Exception 
    { 
      // get input and output streams 
     input = new BufferedReader(new InputStreamReader(client.getInputStream())) ; 
     output = new PrintWriter (client.getOutputStream(),true); 
     output.println("Welcome to Bob's Chat Server!\n"); 
     // read name 
     output.println("Please Enter a User Name: "); 
     name = input.readLine(); 
     users.add(name); // add to vector 
     output.println("Welcome "+name+" we hope you enjoy your chat today"); 
     start(); 
    } 

    public void sendMessage(String uname,String msg) 
    { 
     output.println(uname + ":" + msg); 
    } 

    public String getUserName() 
    { 
     return name; 
    } 

    public void run() 
    { 
     String line; 
     try  
     { 
      while(true) 
      { 
       if (input.readline("EXIT")) 
       { 
        clients.remove(this); 
        users.remove(name); 
        break; 
       } 
       if(input.readline(name)) 
       { 
        System.out.println("OK"); 
       } 
       boradcast(name,line); // method of outer class - send messages to all 
      }// end of while 
     } // try 
     catch(Exception e) 
     { 
      System.out.println(e.getMessage()); 
     } 
    } // end of run() 
    } // end of inner class 
} // end of Server 
+0

"* 작동하지 않음 *"을 확장하십시오. 컴파일 오류? 런타임 에러? 예상치 못한 기능? (무엇을 보았습니까? 무엇을 기대합니까?) – ziesemer

+0

지금 컴파일하면 다음과 같습니다. TCPServer.java:79 : 심볼 심볼을 찾을 수 없습니다. readline (java.lang.String) 위치 : 클래스 java.io.BufferedReader의 \t \t (input.readline ("EXIT")) \t \t^ TCPServer.java:85가있는 경우 : 기호 기호를 찾을 수 없습니다 : 방법의 readline (java.lang.String의) 위치 : 클래스 java.io.BufferedReader의 \t \t 경우 (input.readline ("이름")) \t \t^ 2 개의 오류 – user1174834

+0

채팅 서버 대신 "웹 소켓"을 사용해야합니다. 그것은 그것을하는 현대적인 방법입니다. – djangofan

답변

3

정확히 입력 줄이 현재 사용자 이름과 같을 때 찾고있는 경우가 많습니다. 당신을 위해 무엇을 찾고 :

public void run(){ 
     try{ 
      while(true){ 
       String line = input.readLine(); 

       if("EXIT".equals(line)){ 
        clients.remove(this); 
        users.remove(name); 
        break; 
       }else if(name.equals(line)){ 
        System.out.println("OK"); 
       } 
       boradcast(name, line); // method of outer class - send messages to all 
      }// end of while 
     } // try 
     catch(Exception e){ 
      System.out.println(e.getMessage()); 
     } 
    } // end of run() 

것은이 해결하는 몇 가지 문제 :

  • input.readline는 방법이 아니라 input.readLine입니다 - 그것은 매개 변수를 허용하지 않습니다. (이것은 컴파일 오류로 표시되어야합니다.)
  • line 문자열에는 아무 것도 지정하지 않았습니다.
  • 라인을 여러 번 읽었습니다. "EXIT"와 일치하지 않으면 이전 줄에 대해 사용자가 입력 한 내용을 모두 잃어버린 name과 비교할 새 줄을 읽습니다.
+0

감사합니다. 그만큼 도움이됩니다. input.readLine을 사용하려고했는데 잘못 입력 한 것 같습니다. – user1174834