2011-10-11 2 views
1

간단한 서버 클라이언트 응용 프로그램을 만들고 싶지만 IO 스트림에 문제가 있다고 생각합니다. GUI가 없으므로 채팅은 콘솔을 통해 이루어질 것입니다 (이클립스를 열어 테스트하거나 사용중인 IDE를 열 수 있습니다). 여기 자바 간단한 서버/클라이언트 콘솔 채팅 응용 프로그램

내 서버 코드 :

import java.io.IOException; 
import java.io.ObjectInputStream; 
import java.io.ObjectOutputStream; 
import java.net.ServerSocket; 
import java.net.Socket; 
import java.util.Scanner; 

public class Server { 
    ServerSocket serverSocket; 
    Socket connection; // connection-to-client 
    ObjectOutputStream output; 
    ObjectInputStream input; 

    public void run() { 
     try { 
      serverSocket = new ServerSocket(6000, 100); 
     } catch (IOException e) { 
      System.err.println("Invalid port number"); 
     } 
     while (true) { 
      try { 
       waitForConnection(); 
       getIOStreams(); 
       processConnection(); 
      } finally { 
       closeConnection(); 
      } 
     } 
    } 

    public void closeConnection() { 
     try { 
      input.close(); 
      output.close(); 
      connection.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    public void waitForConnection() { 
     System.out.println("Server is ready to accept conenctions"); 
     try { 
      connection = serverSocket.accept(); // code will stop here until a 
               // connection occurs 
      System.out.println("Conenction established with the client"); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    public void getIOStreams() { 
     try { 
      output = new ObjectOutputStream(connection.getOutputStream()); 
      output.flush(); // send header information to the client, which 
          // contains info required to create the input stream 
          // object 
      input = new ObjectInputStream(connection.getInputStream()); 
      System.out.println("Server established I/O streams"); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    public void processConnection() { 
     sendData("Connection established with the server"); 
     String inputMessage = ""; 
     new Runnable() { 
      Scanner sc = new Scanner(System.in); 

      public void run() { 
       while (true) { 
        sendData(sc.nextLine()); 
       } 
      } 
     }; 
     do { 

      try { 
       inputMessage = (String) input.readObject(); 
       System.out.println(inputMessage); 
      } catch (ClassNotFoundException e) { 
       System.err.println("Object of an unknown type was recieved"); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } while (inputMessage.equals("QUIT")); 
    } 

    public void sendData(String s) { 
     try { 
      output.writeObject(s); 
      output.flush(); 
      System.out.println("Server: " + s); 
     } catch (IOException e) { 
      System.err.println("Error writting the message"); 
     } 
    } 
} 

이이

import java.io.IOException; 
import java.io.ObjectInputStream; 
import java.io.ObjectOutputStream; 
import java.net.ServerSocket; 
import java.net.Socket; 
import java.net.UnknownHostException; 
import java.util.Scanner; 

public class Client { 
    ServerSocket serverSocket; 
    Socket clientSocket; 
    ObjectOutputStream output; 
    ObjectInputStream input; 
    String serverAddress = "127.0.0.1"; 

    public void run() { 
     connect2Server(); 
     getIOStreams(); 
     processConnection(); 
     closeConnection(); 
    } 

    public void connect2Server() { 
     System.out.println("Trying to connect to the server"); 
     try { 
      clientSocket = new Socket(serverAddress, 6000); 
     } catch (UnknownHostException e) { 
      System.err.println("Server unavailable"); 
      System.exit(1); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

    public void getIOStreams() { 
     try { 
      output = new ObjectOutputStream(clientSocket.getOutputStream()); 
      output.flush(); 
      input = new ObjectInputStream(clientSocket.getInputStream()); 
      System.out.println("Client established I/O Stream"); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    public void processConnection() { 
     sendData("Connection established with the client"); 
     String inputMessage = ""; 
     new Runnable() { 
      Scanner sc = new Scanner(System.in); 

      public void run() { 
       String outputMessage = ""; 
       do { 
        outputMessage = sc.nextLine(); 
        sendData("Client: " + outputMessage); 
       } while (outputMessage.equals("QUIT")); 
      } 
     }; 
     while (true) { 

      try { 
       inputMessage = (String) input.readObject(); 
       System.out.println(inputMessage); 
      } catch (ClassNotFoundException e) { 
       System.err.println("Object of an unknown type was recieved"); 
      } catch (IOException e) { 
       e.printStackTrace(); 
       System.exit(1); 
      } 
     } 
    } 

    public void sendData(String s) { 
     try { 
      output.writeObject(s); 
      output.flush(); 
      System.out.println("Client: " + s); 
     } catch (IOException e) { 
      System.err.println("Error writting the message"); 
     } 
    } 

    public void closeConnection() { 
     try { 
      output.close(); 
      input.close(); 
      clientSocket.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

    } 
} 

단지의 주요 클라이언트/server.run에 쓰기 서버 또는 클라이언트를 실행하는 내 클라이언트 코드(); 입력 루프의 끝 부분에 대한

1) 잘못된 조건 :

이이 부정되어야한다
while (inputMessage.equals("QUIT")); // Server#processConnection 

while (outputMessage.equals("QUIT")) // Client#processConnection 

(" 내 오류와 어떻게

+0

코드를 통과하는 것이 너무 습관적입니다 ... 어떤 오류가 발생했는지 또는 예상 한 것을 지정하십시오. – PeterMmm

+0

inputMessage = (String) input.readObject(); 예외는 클라이언트 클래스에서 발생한이 줄에서 발생합니다 ... 내가 무엇을 기대하는 것은 스캐너에서 콘솔에 쓰는 것을 읽으며 서버의 콘솔에 표시되고 그 반대의 경우 – blenddd

답변

3

몇 가지 포인트를 :) 해결하는 방법이 무엇인지 말해주십시오! ").

2) 당신은 당신에게 System.in 읽기 스레드를 시작해야한다 : 클라이언트가 연결이 끊어졌습니다 것을 의미 EOFException처럼

new Thread() { // instead of `Runnable` 
    ... 
}.start(); 

3) 당신은 몇 가지 예외를 서버에서 수신 루프를 중단해야한다.

+0

예, point 1,2 : D thx, ur for 3 points 나는 EOFException을 잡으려고 시도했다. 그러나 그것은 내게 그것을 던질 수 없을 것 같은 어떤 종류의 에러를 주었다. 나는 그것을 잡을 수 없다. 내말은. – blenddd

+0

나는 catch (IOException e) 절 뒤에 catch (EOFException e) 절을 추가하려고했기 때문일 것이다. 후자는 전자를 (EOFException이 IOException을 확장 할 때) 다루고있다. 더 일반적인 예외는보다 구체적인 예외 뒤에 배치해야합니다. – yozh

+0

그래, 그것을 시도하고 지금은 작동하지만, 내가 아는 한 EOFException IOException을 확장하는 경우 다음 IOException을 잡으면, EOFException 던져 질해서는 안됩니다, 그것은 던졌습니다 :/ – blenddd