2017-04-20 3 views
1

Android에서 기본 MQTT 통합을 배우려고합니다. 나는 메시지를 게시하고 구독하기 위해 모스 토 브로커를 사용하고 있습니다. 나는 실제 장치의 코드를 실행하고이 예외를 얻고있다 :ANDROID-MQTT : 서버에 연결할 수 없습니다. (32103)

Unable to connect to server (32103) - java.net.ConnectException: 
    failed to connect to /192.168.0.103 (port 1883) after 
    30000ms: isConnected failed: ECONNREFUSED 

여기 내 코드입니다 :

public class HomeActivity extends AppCompatActivity{ 

    private MqttAndroidClient client; 
    private final MemoryPersistence persistence = new MemoryPersistence(); 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     final MqttAndroidClient mqttAndroidClient = new MqttAndroidClient(this.getApplicationContext(), "tcp://192.168.0.103:1883", "androidSampleClient", persistence); 
     mqttAndroidClient.setCallback(new MqttCallback() { 
      @Override 
      public void connectionLost(Throwable cause) { 
       System.out.println("Connection was lost!"); 
      } 

      @Override 
      public void messageArrived(String topic, MqttMessage message) throws Exception { 
       System.out.println("Message Arrived!: " + topic + ": " + new String(message.getPayload())); 
      } 

      @Override 
      public void deliveryComplete(IMqttDeliveryToken token) { 
       System.out.println("Delivery Complete!"); 
      } 
     }); 

     MqttConnectOptions mqttConnectOptions = new MqttConnectOptions(); 
     mqttConnectOptions.setCleanSession(true); 

     try { 
      mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() { 
       @Override 
       public void onSuccess(IMqttToken asyncActionToken) { 
        System.out.println("Connection Success!"); 
        try { 
         System.out.println("Subscribing to /test"); 
         mqttAndroidClient.subscribe("/test", 0); 
         System.out.println("Subscribed to /test"); 
         System.out.println("Publishing message.."); 
         mqttAndroidClient.publish("/test", new MqttMessage("Hello world testing..!".getBytes())); 
        } catch (MqttException ex) { 

        } 
       } 

       @Override 
       public void onFailure(IMqttToken asyncActionToken, Throwable exception) { 
        System.out.println("Connection Failure!"); 
        System.out.println("throwable: " + exception.toString()); 
       } 
      }); 
     } catch (MqttException ex) { 
      System.out.println(ex.toString()); 
     } 


    } 
    } 

내가 해봤 다른 포트를 사용하지만 오류가 동일합니다. 누구든지 내가 뭘 잘못하고 있는지 도울 수 있니?

+0

오류로 인해 연결이 거부되었으므로 브로커가 해당 포트에서 수신 대기하지 않음을 의미합니다. 브로커 구성 방법에 대한 세부 정보로 질문 업데이트 – hardillb

답변

0

시도하여 포트 8883

String clientId = MqttClient.generateClientId(); 
final MqttAndroidClient client = 
     new MqttAndroidClient(this.getApplicationContext(), "ssl://iot.eclipse.org:8883", 
           clientId); 
try { 
    MqttConnectOptions options = new MqttConnectOptions(); 

     InputStream input = 
       this.getApplicationContext().getAssets().open("iot.eclipse.org.bks"); 

     options.setSocketFactory(client.getSSLSocketFactory(input, "eclipse-password")); 


     IMqttToken token = client.connect(options); 
     token.setActionCallback(new IMqttActionListener() { 
      @Override 
      public void onSuccess(IMqttToken asyncActionToken) { 
       // We are connected 
       Log.d(TAG, "onSuccess"); 

      } 

      @Override 
      public void onFailure(IMqttToken asyncActionToken, Throwable exception) { 
       // Something went wrong e.g. connection timeout or firewall problems 
       Log.d(TAG, "onFailure"); 

      } 
     }); 


} catch (MqttException | IOException e) { 
    e.printStackTrace(); 
} 
+0

브로커 구성 방법을 알지 못하면 다른 포트를 선택하는 것이 도움이되지 않습니다. 당신은 또한 SE가 그들 자신의 것을 운영하기를 원한다면 도움을주지 않을 공공 브로커로 중개인을 바꾸기 위해 솔기를 짠다. – hardillb

1

이 시작되기 때문에, 어떻게 다른 구현 작업을 볼 볼 필요가있다. 내 구현을 한번보세요. 나는 MQTT 특정 항목을 위해 분리 된 클래스를 사용한다.

MqttUtil.java

public class MqttUtil { 
    private static final String MQTT_TOPIC = "test/topic"; 
    private static final String MQTT_URL = "tcp://localhost:1883"; 
    private static boolean published; 
    private static MqttAndroidClient client; 
    private static final String TAG = MqttUtil.class.getName(); 


    public static MqttAndroidClient getClient(Context context){ 
     if(client == null){ 
      String clientId = MqttClient.generateClientId(); 
      client = new MqttAndroidClient(context, MQTT_URL, clientId); 
     } 
     if(!client.isConnected()) 
      connect(); 
     return client; 
    } 

    private static void connect(){ 
     MqttConnectOptions mqttConnectOptions = new MqttConnectOptions(); 
     mqttConnectOptions.setCleanSession(true); 
     mqttConnectOptions.setKeepAliveInterval(30); 

     try{ 
      client.connect(mqttConnectOptions, null, new IMqttActionListener() { 
       @Override 
       public void onSuccess(IMqttToken asyncActionToken) { 
        Log.d(TAG, "onSuccess"); 
       } 
       @Override 
       public void onFailure(IMqttToken asyncActionToken, Throwable exception) { 
        Log.d(TAG, "onFailure. Exception when connecting: " + exception); 
       } 
      }); 
     }catch (Exception e) { 
      Log.e(TAG, "Error while connecting to Mqtt broker : " + e); 
      e.printStackTrace(); 
     } 
    } 

    public static void publishMessage(final String payload){ 
     published = false; 
     try { 
      byte[] encodedpayload = payload.getBytes(); 
      MqttMessage message = new MqttMessage(encodedpayload); 
      client.publish(MQTT_TOPIC, message); 
      published = true; 
      Log.i(TAG, "message successfully published : " + payload); 
     } catch (Exception e) { 
      Log.e(TAG, "Error when publishing message : " + e); 
      e.printStackTrace(); 
     } 
    } 

    public static void close(){ 
     if(client != null) { 
      client.unregisterResources(); 
      client.close(); 
     } 
    } 
} 

그리고 당신은 단순히 HomeActivity에서 사용할 수 있습니다. 아래에서 확인하십시오 :

public class HomeActivity extends AppCompatActivity{ 

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

    // Get Mqtt client singleton instance 
    MqttUtil.getClient(this); 

    // Publish a sample message 
    MqttUtil.publishMessage("Hello Android MQTT"); 
    } 
} 

테스트 목적으로 Mosquitto 하위 클라이언트를 사용하고 메시지가 표시되는지 확인하십시오.

희망 하시겠습니까?