2017-04-20 34 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

只要选择不同的端口,除非我们知道代理的配置方式,否则无济于事。如果OP希望自己经营,那么你们也将经纪人变成了一个公共经纪人,这对他们来说不会有什么帮助 – 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子客户端,看看你得到的消息。

希望有帮助!