import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import javax.net.SocketFactory;
public class MySocketFactory extends SocketFactory {
private SocketFactory socketFactory;
private Socket socket;
public MySocketFactory() {
this.socketFactory = SocketFactory.getDefault();
}
public MySocketFactory(SocketFactory socketFactory) {
this.socketFactory = socketFactory;
}
@Override
public Socket createSocket(String host, int port) throws IOException {
socket = this.socketFactory.createSocket(host, port);
modifySocket();
return socket;
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException {
socket = socketFactory.createSocket(host, port, localHost, localPort);
modifySocket();
return socket;
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
socket = socketFactory.createSocket(host, port);
modifySocket();
return socket;
}
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
socket = socketFactory.createSocket(address, port, localAddress, localPort);
modifySocket();
return socket;
}
@Override
public Socket createSocket() throws IOException {
socket = socketFactory.createSocket();
modifySocket();
return socket;
}
private void modifySocket() throws IOException {
socket.setKeepAlive(true);
socket.setSoTimeout(10 * 1000);
socket.setSoLinger(true, 0);
socket.setTcpNoDelay(true);
}
}
String broker = Statics.broker;
// mqtt paho client id
clientId = MqttClient.generateClientId();
client = new MqttAndroidClient(MyMqttService.this, broker,
clientId, new MemoryPersistence());
MqttConnectOptions options = new MqttConnectOptions();
options.setAutomaticReconnect(false);
options.setCleanSession(true);
options.setUserName(""test");
options.setPassword("test".toCharArray());
options.setConnectionTimeout(20);
options.setKeepAliveInterval(0);
MySocketFactory mySocketFactory=new MySocketFactory();
options.setSocketFactory(mySocketFactory);
Related