안드로이드 장치 (에뮬레이터)와 내 랩톱간에 클라이언트 - 서버 관계를 설정하려고합니다. 소켓은, 데이터가 클라이언트로부터 서버에 최초로 전송 될 때 올바르게 설정되어있는 것처럼 보입니다 만, 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을 만드는 줄에서 멈추는 것은 분명합니다. 어디에도 오류 메시지가 없습니다. 여기서 내가 뭘 잘못하고 있니?
응답 해 주셔서 감사합니다. 나는'ObjectInputStream'과'ObjectOutputStream'의 셋업을'ClientThread'로 옮겼습니다. 이제 버튼 메서드는 다음과 같습니다 : 'String msg = "Hello"; out.writeObject (msg); button.setText ("Message sent"); msg = (문자열) in.readObject(); button.setText ("Message Received");' 서버가 성공적으로 메시지를 수신하지만 클라이언트는 이제'in.readObject()'줄에서 중지하고 있습니다. 서버에서 보낸 메시지를 읽지 않는 이유는 무엇입니까? – Toast
신경 쓰지 마라, 나는 지금 일하고있어, 충고에 감사한다! – Toast