2014-01-07 2 views
0

안드로이드 장치 (에뮬레이터)와 내 랩톱간에 클라이언트 - 서버 관계를 설정하려고합니다. 소켓은, 데이터가 클라이언트로부터 서버에 최초로 전송 될 때 올바르게 설정되어있는 것처럼 보입니다 만, ObjectInputStream를 사용해 입력 스트림을 확립하려고하면 (자), 클라이언트 측에서 프로그램이 정지하고 있습니다. 여기 ObjectInputStream을 사용하면 Android 애플리케이션이 멈 춥니 다. 클라이언트 - 서버 문제

try{ 
     providerSocket = new ServerSocket(6666); 
     connection = providerSocket.accept(); 

     out = new ObjectOutputStream(connection.getOutputStream()); 
     out.flush(); 
     System.out.println("output stream established"); 

     in = new ObjectInputStream(connection.getInputStream()); 
     System.out.println("input stream established"); 

     try{ 
      message = (String)in.readObject(); 
      System.out.println("client>" + message); 
      sendMessage("Thanks for the message!"); 
     } 
     catch(ClassNotFoundException classnot){ 
      System.err.println("Data received in unknown format"); 
     } 
    } 
catch(IOException ioException){ 
    ioException.printStackTrace(); 
} 

안드로이드 장치에 대한 관련 코드이다 : 여기

노트북에서 설치에 서버를 사용하는 코드이다. updatePhotos 메서드는 특정 버튼을 누를 때 호출됩니다. 버튼의 텍스트가 변경되어 코드가 멈추는 위치를 확인할 수 있습니다.

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    new Thread(new ClientThread()).start(); 
} 
public void updatePhotos(View view){ 
    Button button = (Button)findViewById(R.id.button7); 
    try { 
     String msg = "Hello"; 
     ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream()); 
     out.flush(); 

     out.writeObject(msg); 
     out.flush(); 

     button.setText("Establishing Input Stream"); 
     ObjectInputStream in = new ObjectInputStream(socket.getInputStream()); 
     button.setText("Input stream established"); 

     msg = (String)in.readObject(); 
     button.setText(msg); 

     } catch (UnknownHostException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
} 

class ClientThread implements Runnable { 
    @Override 
    public void run() { 
     try { 
      InetAddress serverAddr = InetAddress.getByName(SERVER_IP); 
      socket = new Socket(serverAddr, SERVERPORT); 
     } catch (UnknownHostException e1) { 
      e1.printStackTrace(); 
     } catch (IOException e1) { 
      e1.printStackTrace(); 
     } 
    } 
} 

그래서 서버 프로그램이 먼저 실행 된 다음 안드로이드 응용 프로그램이 에뮬레이터에서 실행됩니다. 첫 번째 앱 활동이 시작되고 소켓 연결이 성공적으로 완료되면 ClientThread가 시작됩니다.

다음으로, 버튼을 클릭하고 프로그램 버튼 텍스트가 "구축 입력 스트림"읽고 이클립스 콘솔이 표시 될 때까지 실행

출력 스트림 설립

입력 스트림 설립

클라이언트> Hello

서버> 메시지를 보내 주셔서 감사합니다!

서버에서 클라이언트로 데이터를 보내고 있음에도 불구하고 프로그램이 클라이언트의 ObjectInputStream을 만드는 줄에서 멈추는 것은 분명합니다. 어디에도 오류 메시지가 없습니다. 여기서 내가 뭘 잘못하고 있니?

답변

0

보낼 때마다 새로운 스트림 집합을 만들지 마십시오. 양쪽 소켓의 소켓 수명은 동일하게 ObjectInputStreamObjectOutputStream을 사용하십시오. 현재 서버에는 ObjectOutputStream이 있고 클라이언트에는 복수 ObjectInputStreams이 있습니다. 처음으로 ObjectInputStream 생성자는 도착하지 않을 객체 스트림 헤더를 기다리는 것을 차단합니다. Javadoc을 보라.

NB 서버는 받아 들여진 소켓을 결코 닫지 않는다는 사실부터 시작하여 많이 필요합니다. 허용 된 소켓 당 새 스레드를 시작하고 해당 스레드에서 스트림 구성을 포함한 모든 I/O를 수행해야합니다.

+0

응답 해 주셔서 감사합니다. 나는'ObjectInputStream'과'ObjectOutputStream'의 셋업을'ClientThread'로 옮겼습니다. 이제 버튼 메서드는 다음과 같습니다 : 'String msg = "Hello"; out.writeObject (msg); button.setText ("Message sent"); msg = (문자열) in.readObject(); button.setText ("Message Received");' 서버가 성공적으로 메시지를 수신하지만 클라이언트는 이제'in.readObject()'줄에서 중지하고 있습니다. 서버에서 보낸 메시지를 읽지 않는 이유는 무엇입니까? – Toast

+0

신경 쓰지 마라, 나는 지금 일하고있어, 충고에 감사한다! – Toast