두 대의 휴대 기기간에 Wi-Fi를 사용하여 통신하고 있습니다. 메시지를 보내고받을 수있는 설치 소켓이 있습니다. 서버 장치 (소유자)를 시작한 다음 클라이언트 장치 (구성원)를 시작하면 모든 것이 잘 작동합니다. 순서에 관계없이 모든 장치를 시작하고 메시지를 계속 보내고 싶습니다.클라이언트가 서버 소켓 연결을 기다리는 것을 어떻게 만드나요?
현재 클라이언트는 5 초 동안 대기하고 연결이 가능하지 않으면 서버 찾기를 중지합니다. 클라이언트가 서버 연결을 찾을 때까지 시간 초과 후에도 서버를 계속 찾고 싶습니다. 나는 이것을 시도하고 아직 이것을 성공적으로 구현하지 못했습니다.
초기 클라이언트 코드 : 내 코드에
@Override
public void run() {
Socket socket = new Socket();
try {
socket.setReuseAddress(true);
socket.bind(null);
while(!connectedToServer) {
try {
socket.connect(new InetSocketAddress(address.getHostAddress(), SERVER_PORT),
TIME_OUT);
socketCreator = new SocketReadWriter(socket, handler);
new Thread(socketCreator).start();
connectedToServer = true;
} catch (ConnectException e) {
Log.i(TAG,"Error while connecting. " + e.getMessage());
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} catch (Exception e){
Log.i(TAG,"Exception "+e.getMessage());
}
}
} catch (IOException e) {
e.printStackTrace();
try {
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
누락 무엇 :
@Override
public void run() {
Socket socket = new Socket();
try {
socket.bind(null);
socket.connect(new InetSocketAddress(address.getHostAddress(), SERVER_PORT), TIME_OUT);
socketCreator = new SocketCreator(socket, handler);
new Thread(socketCreator).start();
} catch (IOException e) {
e.printStackTrace();
try {
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return;
}
}
다음과 같이 수정? 어떻게 작동시킬 수 있습니까?
나는 계속이 오류를 얻고있다 :
Exception java.io.IOException: fcntl failed: EBADF (Bad file number)
관련 질문 : http://stackoverflow.com/questions/7312794/retry-a-connection-on-timeout-in-java. 또한'catch '가 아닌'finally' 블록에서'socket.close()'를 호출해야합니다. – user991710
나는 다시 시도했다 .. 나는 이것을 얻고있다 : 예외 java.io.IOException : fcntl 실패 : EBADF (잘못된 파일 번호) – NewOne