I am using Eclipse Paho Java Client to connect. Here is my extended callback:
protected IMqttAsyncClient mClient;
private final MqttCallbackExtended mCallback = new MqttCallbackExtended() {
#Override
public void connectComplete(boolean reconnect, String brokerAddress) {
Log.d(LOG_TAG, "connectComplete " + brokerAddress);
}
#Override
public void connectionLost(Throwable ex) {
Log.d(LOG_TAG, "connectionLost", ex);
}
#Override
public void deliveryComplete(IMqttDeliveryToken deliveryToken) {
Log.d(LOG_TAG, "deliveryComplete " + deliveryToken);
}
#Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
Log.d(LOG_TAG, "messageArrived " + topic);
}
};
And here the connecting code:
protected void connect() throws MqttException {
Log.d(LOG_TAG, "connect");
MqttConnectOptions connectOptions = new MqttConnectOptions();
connectOptions.setCleanSession(true);
connectOptions.setAutomaticReconnect(false);
connectOptions.setUserName(MQTT_USERNAME);
connectOptions.setPassword(MQTT_PASSWORD.toCharArray());
mClient = new MqttAsyncClient(mBrokerUri, mClientName, new MemoryPersistence());
mClient.setCallback(mCallback);
mClient.connect(connectOptions);
Debug d = ((MqttAsyncClient) mClient).getDebug();
d.dumpClientDebug();
}
I do not use the automatic reconnect feature, but would like to handle reconnecting in my own custom code, since I need custom delays.
For testing purposes I do not start MQTT broker yet and try to connect.
I was hoping to detect the initial connection failure in the connectionLost callback method, but it does not get called.
The MqttException is not thrown either.
When I inspect the paho0.log.0 log file I see the failed connection there -
FINE 17-03-09 07:55:33.0726 al.TCPNetworkModule start 61 ef978a39c826cd6d4ad22f20d5abe6c236eddb060b5d765a1fe2e1d79837fcc8: Failed to create TCP socket
Throwable occurred: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule.start(TCPNetworkModule.java:70)
at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:650)
at java.lang.Thread.run(Thread.java:745)
FINE 17-03-09 07:55:33.0727 nternal.ClientComms connectBG:run 61 ef978a39c826cd6d4ad22f20d5abe6c236eddb060b5d765a1fe2e1d79837fcc8: connect failed: unexpected exception
Throwable occurred: Unable to connect to server (32103) - java.net.ConnectException: Connection refused: connect
at org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule.start(TCPNetworkModule.java:79)
at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:650)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule.start(TCPNetworkModule.java:70)
... 2 more
FINE 17-03-09 07:55:33.0732 nternal.ClientComms shutdownConnection 61 ef978a39c826cd6d4ad22f20d5abe6c236eddb060b5d765a1fe2e1d79837fcc8: state=DISCONNECTING
FINE 17-03-09 07:55:33.0732 ernal.CommsCallback stop 61 ef978a39c826cd6d4ad22f20d5abe6c236eddb060b5d765a1fe2e1d79837fcc8: stopped
FINE 17-03-09 07:55:33.0733 nal.CommsTokenStore quiesce 61 ef978a39c826cd6d4ad22f20d5abe6c236eddb060b5d765a1fe2e1d79837fcc8: resp=Client is currently disconnecting (32102)
But how to detect that connection failure in my code? (So that I could initiate the later reconnection).
UPDATE:
Reported this issue as Bug #336
Currently the only way to detect the initial connect failure of an async client is to pass it one more callback:
private final IMqttActionListener mConnectionCallback = new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d(LOG_TAG, "onSuccess " + asyncActionToken);
// do nothing, this case is handled in mCallback.connectComplete method
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable ex) {
Log.d(LOG_TAG, "onFailure " + asyncActionToken, ex);
// initial connect has failed
}
};
mClient = new MqttAsyncClient(mBrokerUri, mClientName, new MemoryPersistence());
mClient.setCallback(mCallback);
mClient.connect(connectOptions, null, mConnectionCallback);
Related
In my app, MongoDB 3.2.4 runs on a custom port, I want to implement logic where my app will try to reach MongoDB on a custom port and if it fails it will use the default 27018 port.
In order to do that I use the following code:
String mongoClientURI = "mongodb://" + DB_SRV_USR + ":" + DB_SRV_PWD + "#" + DB_URL + ":" + DB_PORT_CUS + "/" + dbName;
MongoClientURI connectionString = new MongoClientURI(mongoClientURI);
// enable SSL connection
MongoClientOptions.builder().sslEnabled(true).build();
if (this.mongoClient == null) {
this.mongoClient = new MongoClient(connectionString);
}
// create database if doesn't exist
MongoDatabase mdb = this.mongoClient.getDatabase(dbName);
try {
this.mongoClient.getAddress();
} catch (com.mongodb.MongoSocketOpenException e) {
System.out.println("Switch to default port");
/*…use default port logic…*/
}
The problem is that this exception is not caught.
Although MongoDB throws the following exception:
com.mongodb.MongoSocketOpenException: Exception opening socket at
com.mongodb.connection.SocketStream.open(SocketStream.java:63) at
com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:114)
at
com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:128)
at java.lang.Thread.run(Thread.java:745) Caused by:
java.net.ConnectException: Connection refused: connect at
java.net.DualStackPlainSocketImpl.waitForConnect(Native Method) at
java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
at
java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at
java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at
java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) at
java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at
java.net.Socket.connect(Socket.java:589) at
com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:50)
at com.mongodb.connection.SocketStream.open(SocketStream.java:58)
... 3 more
my try-catch expression can't catch this exception.
I tried multiple approaches, such as to catch:
Exception
RuntimeException
MongoSocketOpenException
MongoException
MongoCommandException
none of them doesn't work.
My questions:
How can I check if MongoDB connection is established?
How can catch the exception MongoSocketOpenException?
I use this code to check connection:
try {
mongo.getAddress();
} catch (Exception e) {
System.out.println("Database unavailable!");
mongo.close();
return;
}
Not sure here my guess would be that this.mongoClient.getAddress(); does not throw that exception, but I don't really know
EDIT: I initialized it via:
Builder builder = MongoClientOptions.builder().connectTimeout(3000);
MongoClient mongo = new MongoClient(new ServerAddress("192.168.0.1", 3000), builder.build());
I am getting "java.io.eof" exception,when i am trying to subscribe mqtt client. I am using eclipse paho library and using mosquitto broker. I am not getting any answer of this,so please help me why this happens ?
Mqtt connection and subscribe
I am using this code for connecting and subscribing to mosquitto
private void buildClient(String clientId){
log.debug("Connecting... "+clientId);
try {
mqttClient = new MqttClient(envConfiguration.getBrokerUrl(), clientId,new MemoryPersistence());
System.out.println(mqttClient.isConnected());
} catch (MqttException e) {
log.debug("build client stopped due to "+e.getCause());
}
chatCallback = new ChatCallback(this.userService,this);
mqttClient.setCallback(chatCallback);
mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setCleanSession(true);
}
#Override
public void connect(String clientId,String topic) {
try{
if(mqttClient == null || !mqttClient.getClientId().equals(clientId)){
buildClient(clientId);
mqttClient.connect(mqttConnectOptions);
subscribe(clientId,topic);
}
}catch (Exception e) {
log.debug("connection attempt failed "+ e.getCause() + " trying...");
}
}
#Override
public void subscribe(String clientId,String topic) throws MqttException {
if(mqttClient != null && mqttClient.isConnected()){
mqttClient.subscribe(topic,0);
/*try {
log.debug("Subscribing... with client id :: " + clientId + "topic");
mqttClient.subscribe(topic,2);
} catch (MqttException e) {
log.debug("subscribing error.."+e.getLocalizedMessage());
}*/
}
}
}
And mqtt call back
#Override
public void connectionLost(Throwable arg0) {
log.debug("Connection lost... attampting retrying due to "
+ arg0);
arg0.printStackTrace();
// chatServiceimpl.connect();
}
#Override
public void deliveryComplete(IMqttDeliveryToken arg0) {
log.debug("delivered message" + arg0);
// TODO Auto-generated method stub
}
#Override
public void messageArrived(String arg0, MqttMessage arg1) throws Exception {
log.debug("Message recived..." + arg1.toString());
userService.saveChat(arg1.toString());
}
I am facing this error when i am subscribing to mosquitto
Error logs
2015-11-30/18:19:00.877 [MQTT Call: 25287] DEBUG c.s.s.ChatCallback: Message recived...{ "id":"37153topic25287T1448886285.79573", "from":"37153", "to":"25287", "chatBody":[{"type": "text", "message":"The fact "}]}
2015-11-30/18:19:00.878 [MQTT Call: 25287] DEBUG c.s.s.u.UserService: Saving chat...
2015-11-30/18:19:00.883 [MQTT Call: 25287] DEBUG c.s.s.u.UserService: Get user by id::37153
2015-11-30/18:19:00.885 [MQTT Call: 25287] DEBUG c.s.s.u.UserService: Get user by id::25287
2015-11-30/18:19:00.886 [MQTT Rec: 25287] DEBUG c.s.s.ChatCallback: Connection lost... attampting retrying due to Connection lost (32109) - java.io.EOFException
Connection lost (32109) - java.io.EOFException
at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:138)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.EOFException
at java.io.DataInputStream.readByte(DataInputStream.java:267)
at org.eclipse.paho.client.mqttv3.internal.wire.MqttInputStream.readMqttWireMessage(MqttInputStream.java:56)
at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:100)
... 1 more
Mosquitto Logs
1448889230: Client 25287 disconnected.
1448889230: New client connected from 192.168.2.63 as 25287 (c0, k60).
1448889231: New connection from 192.168.2.242 on port 1883.
1448889231: Client 25287 already connected, closing old connection.
1448889231: Client 25287 disconnected.
1448889231: New client connected from 192.168.2.242 as 25287 (c1, k60).
1448889231: New connection from 192.168.2.63 on port 1883.
1448889231: Client 25287 already connected, closing old connection.
1448889231: Client 25287 disconnected.
1448889231: New client connected from 192.168.2.63 as 25287 (c0, k60).
1448889269: New connection from 192.168.2.242 on port 1883.
You have multiple clients connecting to the broker with the same clientid, this is not allowed and as one connects the broker will disconnect the currently connected client.
If both clients have automatic reconnection logic then they will just continue to kick each other off.
Change the client id on one of the clients.
As hardillb mentioned above, you have multiple clients connecting. Server (mosquitto) will disconnect the old connection when it receives a connect request from the same client again.
use the isConnected() method on MqttClient object to know if its connected. for eg.
if (! m_client.isConnected()) {
// reconnect
}
I am trying to access an amazon queue using java sdk. The queue is set in an environment with EC2 instance roles so I do not need to use credentials to access it.
Here is my code
public AWSSimpleQueueServiceClient(String queueName, String endPoint) {
try{
this.queueName = queueName;
logger.debug("Queue Name = " + this.queueName + "Endpoint = " + endPoint);
this.sqs = new AmazonSQSClient(new InstanceProfileCredentialsProvider());
if(endPoint != null) {
this.sqs.setEndpoint(endPoint);
}
} catch (Exception e) {
logger.error("Exception while creating AWS SQS Client = " + e.getMessage());
}
}
QueueName and Endpoint are got from configuration files.
I try to send/receive messages from the queue but it gives me the following exception
Exception in thread "main" com.amazonaws.services.sqs.model.QueueDoesNotExistException: The specified queue does not exist or you do not have access to it. (Service: AmazonSQS; Status Code: 400; Error Code: AWS.SimpleQueueService.NonExistentQueue; Request ID: c30b2c9a-0e62-560d-9306-628ebff676d8)
at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:1160)
at com.amazonaws.http.AmazonHttpClient.executeOneRequest(AmazonHttpClient.java:748)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:467)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:302)
at com.amazonaws.services.sqs.AmazonSQSClient.invoke(AmazonSQSClient.java:2422)
at com.amazonaws.services.sqs.AmazonSQSClient.getQueueUrl(AmazonSQSClient.java:541)
at com.ensighten.inform.sqsClient.AWSSimpleQueueServiceClient.getQueueUrl(AWSSimpleQueueServiceClient.java:66)
However, when I try to access the queue using the curl command, I get a response
aws sqs receive-message --queue-url <Endpoint>/031143137427/<QueueName> -- region us-east-1
{
"Messages": [
{
"Body": "Test",
"ReceiptHandle": "AQEBA49LjMDLPyyl4QKwHx9/oVFDV7mZDiOOpdKS/IC2zR3GNblg2IoHuqWBgr5iw7URCkL03Dm23TCs0Z2hB2DIzU+9qxZTOa9Ti57eiHOyAL2XAlbk7TAqGCR4lcsdSW8+LJ5zWCTkBUg5iZOqy4P0KFTfI7KtJJb2aAmeWJpApu+yJRTNAkYtdN91EcYOVFHqc1p6HJmtvvW6vJwfHB5JEbagXdfWwH3/UnJ/O36JwuFoLDp/NBRu6TO+bmYxeZmCN4GdhHuT0a11weki6Ez47Ln63G11LeQ4SFdZTC7QOWflypf8FSbG8W4JGGPZ8J8iWTkW7PGGw6DRavSu97rx3w==",
"MD5OfBody": "1f871ceacd9f4028ed371e91400efe80",
"MessageId": "0f6290d2-4554-4d96-8f93-7564ef667feb"
}
]
}
This is an exception that I get when I try it on another machine setup with EC2 roles.
Exception in thread "main" com.amazonaws.AmazonClientException: Unable to load credentials from Amazon EC2 metadata service
at com.amazonaws.auth.InstanceProfileCredentialsProvider.handleError(InstanceProfileCredentialsProvider.java:244)
at com.amazonaws.auth.InstanceProfileCredentialsProvider.loadCredentials(InstanceProfileCredentialsProvider.java:225)
at com.amazonaws.auth.InstanceProfileCredentialsProvider.getCredentials(InstanceProfileCredentialsProvider.java:124)
at com.amazonaws.services.sqs.AmazonSQSClient.invoke(AmazonSQSClient.java:2413)
at com.amazonaws.services.sqs.AmazonSQSClient.getQueueUrl(AmazonSQSClient.java:541)
at com.ensighten.inform.sqsClient.AWSSimpleQueueServiceClient.getQueueUrl(AWSSimpleQueueServiceClient.java:74)
at com.ensighten.inform.sqsClient.AWSSimpleQueueServiceClient.getMessagesFromQueue(AWSSimpleQueueServiceClient.java:93)
at com.ensighten.inform.jobRunner.TestJobRunner.execute(TestJobRunner.java:96)
at com.ensighten.inform.jobRunner.TestJobRunner.main(TestJobRunner.java:90)
Caused by: java.net.SocketTimeoutException: connect timed out
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at sun.net.NetworkClient.doConnect(NetworkClient.java:175)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:432)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:527)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:211)
at sun.net.www.http.HttpClient.New(HttpClient.java:308)
at sun.net.www.http.HttpClient.New(HttpClient.java:326)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:996)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:932)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:850)
at com.amazonaws.internal.EC2MetadataClient.readResource(EC2MetadataClient.java:90)
at com.amazonaws.internal.EC2MetadataClient.getDefaultCredentials(EC2MetadataClient.java:55)
at com.amazonaws.auth.InstanceProfileCredentialsProvider.loadCredentials(InstanceProfileCredentialsProvider.java:186)
... 7 more
This is how I get the URL of the queue. Tried doing it two ways below. It errors out with the above exception
public String getQueueUrl() {
GetQueueUrlRequest queueUrlRequest = new GetQueueUrlRequest(this.queueName);
logger.debug("Queue Name... = " + this.queueName);
//FIRST WAY -----------> EXCEPTION on the line below
System.out.println("Queue URL .....= " + this.sqs.getQueueUrl(this.queueName));
//SECOND WAY
return this.sqs.getQueueUrl(queueUrlRequest).getQueueUrl();
}
I have been trying to figure this out for a while now. Any help is appreciated.
I am quite a beginner with NetBeans and Java, so I'm pretty sure my questions are very basic but trying to find the solution for 2 weeks I am totally stuck
This is the problem:
I want to implement a RMI Server Client application
So first step was trying with NetBeans to have one work from the net
I used the oracle tutorial to have the first part implemented
http://docs.oracle.com/javase/tutorial/rmi/server.html
My problem is not that the client does not connect, but that the server can't even register in the port I give him. The IP in the error message is my private IP.
This is the error message I get:
Conectando a: 127.0.0.1 / 19400 / PlanificadorTalsa
ServidorPlanificadorStarter exception:
java.rmi.ConnectException: Connection refused to host: 192.168.0.55; nested exception is:
java.net.ConnectException: Connection refused: connect
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619)
at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:342)
at sun.rmi.registry.RegistryImpl_Stub.rebind(Unknown Source)
at Starter.ServidorPlanificadorStarter.main(ServidorPlanificadorStarter.java:52)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:345)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at java.net.Socket.<init>(Socket.java:434)
at java.net.Socket.<init>(Socket.java:211)
at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40)
at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:148)
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613)
... 5 more
I am running windows 8.1, and disabled firewall. I am also using a security file granting all permissions
this is my java code I execute from NetBeans:
import Conexion.DatosConexion;
import Servidor.*;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class ServidorPlanificadorStarter implements InterfazServidorPlanificador {
private static String ip;
private static String Servidor = "SERVIDORNUBE";
private static int puerto;
private static String nombreServidor;
public ServidorPlanificadorStarter(){
super();
}
public static void main(String[] args) {
if (System.getSecurityManager() == null) {
System.setSecurityManager(new SecurityManager());
}
try {
DatosConexion datos = DatosConexion.getInstance();
ip = datos.getServiceIP(Servidor);
puerto = Integer.valueOf(datos.getServicePort(Servidor));
nombreServidor = datos.getServiceName(Servidor);
System.setProperty("java.rmi.server.hostname", ip);
System.out.println("Conectando a: " + ip + " / " + puerto + " / " + nombreServidor);
InterfazServidorPlanificador engine = new ServidorPlanificadorStarter();
InterfazServidorPlanificador stub =
(InterfazServidorPlanificador) UnicastRemoteObject.exportObject(engine, puerto);
Registry registry = LocateRegistry.getRegistry();
registry.rebind(nombreServidor, stub);
System.out.println("ServidorPlanificador bound");
} catch (Exception e) {
System.err.println("ServidorPlanificadorStarter exception:");
e.printStackTrace();
}
}
}
The interface is as follows (very basic, as I have done nothing with it)
public interface InterfazServidorPlanificador extends Remote {
//void addObserver(RemoteObserver o) throws RemoteException;
}
Did you start RMI registry as in tutorial?
http://docs.oracle.com/javase/tutorial/rmi/running.html
I'm trying to authenticate with the Asterisk server, but I am getting this error:
Exception in thread "main" java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at net.sf.asterisk.io.impl.SocketConnectionFacadeImpl.<init> SocketConnectionFacadeImpl.java:52)
at net.sf.asterisk.manager.DefaultManagerConnection.createSocket(DefaultManagerConnection.java:541)
at net.sf.asterisk.manager.DefaultManagerConnection.connect(DefaultManagerConnection.java:530)
at net.sf.asterisk.manager.DefaultManagerConnection.login(DefaultManagerConnection.java:418)
at net.sf.asterisk.manager.DefaultManagerConnection.login(DefaultManagerConnection.java:377)
at call.HelloManager.run(HelloManager.java:48)
at call.HelloManager.main(HelloManager.java:66)
Here is my code:
public class HelloManager
{
private ManagerConnection managerConnection;
public HelloManager() throws IOException
{
ManagerConnectionFactory factory = new ManagerConnectionFactory();
this.managerConnection = factory.getManagerConnection(host, port,
user, password);
}
public void run() throws IOException, AuthenticationFailedException,
TimeoutException
{
OriginateAction originateAction;
ManagerResponse originateResponse;
originateAction = new OriginateAction();
originateAction.setChannel(" SIP/2.0/UDP");
originateAction.setContext("default");
originateAction.setExten("101");
originateAction.setPriority(new Integer(1));
originateAction.setTimeout(new Integer(30000));
// connect to Asterisk and log in
managerConnection.login();
// send the originate action and wait for a maximum of 30 seconds for Asterisk
// to send a reply
// originateResponse = managerConnection.sendAction(originateAction, 30000);
// // print out whether the originate succeeded or not
// System.out.println(originateResponse.getResponse());
// and finally log off and disconnect
// managerConnection.logoff();
}
public static void main(String[] args) throws Exception
{
HelloManager helloManager;
helloManager = new HelloManager();
helloManager.run();
}
}
Can anybody help me fix this?
You need check settings in /etc/asteirsk/manger.conf
Most likly it binded to 127.0.0.1 address or disabled at all.
Also it can be issue with firewall(local or remote), port 5038 tcp have be allowed.