当我尝试在3G连接上运行我的应用程序时,它尝试连接大约1或2分钟,然后抛出异常,它在wifi上运行得很好,但在3G上运行不好。我试过在不同的网络上与不同的人打电话。为什么它不能连接?
它抛出的异常是MQTT异常
Unable to connect to server
这是我称之为MQTT的类,它创建了一个新线程:
public class MQTTService extends Service {
ContextWrapper c = this;
private MqttClient mqttClient;
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onStart(Intent intent, int startId) {
Thread background = new Thread(new Runnable() {
final String BROKER_URL = "tcp://gateway.thebroker.com:1883";
final String clientId = "android-client90";
public void run() {
Looper.prepare();
try{
MqttClient mqttClient = new MqttClient(BROKER_URL, clientId, new MemoryPersistence());
MqttConnectOptions opts = new MqttConnectOptions();
opts.setKeepAliveInterval(600);
opts.setUserName("nabin");
opts.setPassword("M4rk3r".toCharArray());
Log.e("Before Callback", "Connecting..."); // Code works till here if callback is set then errors galore
//mqttClient.setCallback(handler.obtainMessage());
mqttClient.setCallback(new PushCallback(c));
mqttClient.connect(opts);
mqttClient.subscribe("house/pill/notification/bad");
mqttClient.subscribe("house/pill/notification/good");
mqttClient.subscribe("house/pill/notification/skip");
mqttClient.subscribe("house/pill/notification/alert");
mqttClient.subscribe("house/pill/notification/snooze");
mqttClient.subscribe("house/pill/schedule/response");
mqttClient.subscribe("house/pill/nextPill/response");
Log.e("CONNECTED!", "COOOONNECTED!!!!!");
}catch(MqttException e){
Log.e("Internet Error", "No connection available " + e.getMessage() );
}catch(Exception e){
Log.e("ERRRRRORRRRR ", e.getMessage());
}
}
});
background.start();
}
}
谢谢你的帮助!
如果您想从另一个网络访问服务器,它需要一个全球唯一的公共ip地址。从本地网络,通过wifi,它不需要是公共的,请求发出,它在离开路由器之前找到地址。
你在互联网提供商那里得到了私人ip地址,这意味着他们通过路由器(NAT网络)给你ip。你可以向外交流,但没有人能从另一个网络联系到你。
如果你打电话给你的互联网提供商,你可以要求提供你的ip地址以将其公开。对我来说,这是一种经验,四分之三的支持者不知道什么是公共ip地址,他们问:你是说静态的。。不平民的说服他们。
您的wifi连接与您的经纪人连接在同一网络中,而您的3G连接则试图通过互联网连接到您的经纪人。您的3G连接必须能够通过端口1883
连接到主机gateway.thebroker.com
。
如果你想要一个便宜的公共IP地址,我推荐https://www.digitalocean.com/pricing/5美元/月,按小时计费我的意思是$0.007/小时。然后,您可以使用任何在线教程轻松安装Mosquitto Broker。
或者,您可以使用公共开放服务器,使用以下任意一种测试MQTT:http://mqtt.org/wiki/doku.php/public_brokers问题是,它们可能很慢,因为任何人都可以使用它们。但是,是的,别人说的是真的。您的手机通过WLAN(无线局域网)连接,但您的3G/4G服务无法到达该地址。