ManagedChannel managedChannel = ManagedChannelBuilder
.forAddress("localhost", 9090)
.usePlaintext().build();
System.out.println("State: " + managedChannel .getState(false)) // State: IDLE
Grpc.Stub stub = Grpc.newStub(managedChannel);
System.out.println("State: " + managedChannel .getState(false)) // State: IDLE
stub.callMethod();
System.out.println("State: " + managedChannel .getState(false)) // State: IDLE
Above code is GRPC client. It get connection with grpc server. But every time the channel state is IDLE? When is CONNECTING and READY state? Whats wrong?
It is required to wait for another state.
The following code prints connection state: TRANSIENT_FAILURE when server is not started and connection state: READY when it is healthy.
gRPC version: 1.24.0
ManagedChannel managedChannel = ManagedChannelBuilder
.forAddress("localhost", 9090)
.usePlaintext().build();
ConnectivityState state = channel.getState(true);
while (state == ConnectivityState.IDLE || state == ConnectivityState.CONNECTING) {
state = channel.getState(true);
}
System.out.println("connection state: " + state.toString());
Related
I connect to external host successfully
void createConnection()
{
logger.info("Connecting to " + host_ + ":" + port_);
Socket sock_ = new Socket(host_, port_);
}
Connection is executed successfully, however I need to implement a reconnection mechanism, that is triggered when host is down/killed, and subsequently reconnect to A new host and port.
Is there such mechanism in JDK? Something like trigger event or Observer?
I am working on homework about thread synchronization. The method reduceLoad() cannot be accessed when I call this method. All print function inside the reduceLoad() method are never called. If I can't run this method, the key will never be released.
It might be caused by Semaphore.accquire() and Semaphore.realse(). So I tried to delete all Semaphore methods that may cause the problem.
Protion of the program result below:
As you can see the program is held after all threads print "disembarks from ferry at port "
..... omit some result here....
Arrive at port 1 with a load of 5 vehicles
Auto 4 arrives at port 0
Ambulance 1 arrives at port 1
Ambulance 1 boards the ferry at port 1
Auto 6 boards on the ferry at port 1
Auto 8 boards on the ferry at port 1
Auto 0 disembarks from ferry at port 1
Auto 2 disembarks from ferry at port 1
Auto 1 disembarks from ferry at port 1
Ambulance 0 disembarks the ferry at port 1
Auto 7 boards on the ferry at port 1
Auto 3 disembarks from ferry at port 1
This is where the function is called
// Arrive at the next port
port = 1 - port;
// wait for ferry arrives
while (fry.getPort() != port) {
try {
sleep(1000);
} catch (Exception e) {
}
}
// disembarking
System.out.println("Auto " + id_auto + " disembarks from ferry at port " + port);
logger.check(fry.getPort() == port, "error unloading at wrong port");
fry.reduceLoad(); // Reduce load
System.out.println("Auto " + id_auto + " successfully disembarks from ferry at port " + port);
This method reduceLoad() should release a key when the ferry is empty, this key is used to notify other threads to continue adding more cars into the ferry
public synchronized void reduceLoad() {
logger.check(load > 0, "error unloading an empty Ferry!");
load = load - 1;
System.out.println("removed load, now " + load);
if (load == 0) {
unloadingDone.release();
}
}
I have written mqtt client in java for mosquitto broker . it works for while but after sometime if there is no traffic between my client and mqtt broker it gets disconnected with following error:
org.eclipse.paho.client.mqttv3.internal.ClientState.checkForActivity : Timed out as no activity, keepAlive=30,000 lastOutboundActivity=1,493,194,287,903 lastInboundActivity=1,493,194,270,964 time=1,493,194,317,903 lastPing=1,493,194,287,903
How do i stay connected to mqtt broker continuously?
what configuration settings do i need to make ?
My current configuration of mqtt client are (following is just a snippet):
final String brokerUrl = AppProperties.getProperty(AppConstants.MQTT_BROKER);
final String clientId = "";
final String topic = AppProperties.getProperty(AppConstants.MQTT_TOPIC);
MemoryPersistence persistence = new MemoryPersistence();
try {
MqttClient sampleClient = new MqttClient(brokerUrl, clientId, persistence);
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
if(!sampleClient.isConnected()){
sampleClient.connect(connOpts);
}
LOGGER.info("Mqtt Connected to broker: "+ brokerUrl);
sampleClient.setCallback(this);
sampleClient.subscribe(topic);
LOGGER.info("Subscribed");
LOGGER.info("Listening");
}
On Broker in the logs i am getting following error :
1493181236: Socket error on client , disconnecting.
Any help is appreciated.
Thank you.
I had the same problem. After trying many different parameters, the following parameters is stable for me. Hope it helps.
final MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
connOpts.setUserName(userName);
connOpts.setPassword(passWord.toCharArray());
connOpts.setConnectionTimeout(60); // This value, measured in seconds, defines the maximum time interval the client will wait for the network connection to the MQTT server to be established
connOpts.setKeepAliveInterval(30); // This value, measured in seconds, defines the maximum time interval between messages sent or received
connOpts.setAutomaticReconnect(true);
I need to store SMS (when they arrive to the GSM modem) in MySQL.
I have read the docs, but it says to use the smsserver and the conffile.
Then I read that I should use database.java.
Can someone guide me on this?
I am already using the ReadMessages.java and I have achieved storing in a MySQL database, but I have managed to store only the ones that are in the SIM card memory, not the inbound messages.
The inbound messages are just printed by the console, I read that this can do with threads.
This is my code:
public void doIt() throws Exception
{
// Define a list which will hold the read messages.
List<InboundMessage> msgList;
// Create the notification callback method for inbound & status report
// messages.
InboundNotification inboundNotification = new InboundNotification();
// Create the notification callback method for inbound voice calls.
CallNotification callNotification = new CallNotification();
//Create the notification callback method for gateway statuses.
GatewayStatusNotification statusNotification = new GatewayStatusNotification();
OrphanedMessageNotification orphanedMessageNotification = new OrphanedMessageNotification();
try
{
//System.out.println("Example: Read messages from a serial gsm modem.");
//System.out.println(Library.getLibraryDescription());
//System.out.println("Version: " + Library.getLibraryVersion());
// Create the Gateway representing the serial GSM modem.
SerialModemGateway gateway = new SerialModemGateway("modem.com1", "COM4", 115200, "Huawei", "E160");
// Set the modem protocol to PDU (alternative is TEXT). PDU is the default, anyway...
gateway.setProtocol(Protocols.PDU);
// Do we want the Gateway to be used for Inbound messages?
gateway.setInbound(true);
// Do we want the Gateway to be used for Outbound messages?
gateway.setOutbound(true);
// Let SMSLib know which is the SIM PIN.
gateway.setSimPin("0000");
// Set up the notification methods.
Service.getInstance().setInboundMessageNotification(inboundNotification);
Service.getInstance().setCallNotification(callNotification);
Service.getInstance().setGatewayStatusNotification(statusNotification);
Service.getInstance().setOrphanedMessageNotification(orphanedMessageNotification);
// Add the Gateway to the Service object.
Service.getInstance().addGateway(gateway);
// Similarly, you may define as many Gateway objects, representing
// various GSM modems, add them in the Service object and control all of them.
// Start! (i.e. connect to all defined Gateways)
Service.getInstance().startService();
// Printout some general information about the modem.
System.out.println();
System.out.println("Informacion del modem:");
System.out.println(" Fabricante: " + gateway.getManufacturer());
System.out.println(" Modelo: " + gateway.getModel());
System.out.println(" Serial No: " + gateway.getSerialNo());
System.out.println(" SIM IMSI: " + gateway.getImsi());
//System.out.println(" Signal Level: " + gateway.getSignalLevel() + " dBm");
//System.out.println(" Battery Level: " + gateway.getBatteryLevel() + "%");
System.out.println();
// In case you work with encrypted messages, its a good time to declare your keys.
// Create a new AES Key with a known key value.
// Register it in KeyManager in order to keep it active. SMSLib will then automatically
// encrypt / decrypt all messages send to / received from this number.
Service.getInstance().getKeyManager().registerKey("+306948494037", new AESKey(new SecretKeySpec("0011223344556677".getBytes(), "AES")));
// Read Messages. The reading is done via the Service object and
// affects all Gateway objects defined. This can also be more directed to a specific
// Gateway - look the JavaDocs for information on the Service method calls.
ConexionMySQL mysql = new ConexionMySQL();
Connection cnn = mysql.Conectar();
String sms= "";
String originator="";
String sql ="";
int n = 0;
String success="Mensajee satisfactorio";
msgList = new ArrayList<InboundMessage>();
Service.getInstance().readMessages(msgList, MessageClasses.ALL);
for (InboundMessage msg : msgList){
//System.out.println(msg);
sms = msg.getText().toString();
remitente = msg.getOriginator().toString();
//fecha = msg.getDate().getTime();
sql ="INSERT INTO message(message, originator) VALUES (?,?)";
PreparedStatement post = (PreparedStatement) cnn.prepareStatement(sql);
post.setString(1, message);
post.setString(2, originator);
//post.setDate(3, fecha); public void doIt() throws Exception
{
// Define a list which will hold the read messages.
List<InboundMessage> msgList;
// Create the notification callback method for inbound & status report
// messages.
InboundNotification inboundNotification = new InboundNotification();
// Create the notification callback method for inbound voice calls.
CallNotification callNotification = new CallNotification();
//Create the notification callback method for gateway statuses.
GatewayStatusNotification statusNotification = new GatewayStatusNotification();
OrphanedMessageNotification orphanedMessageNotification = new OrphanedMessageNotification();
try
{
//System.out.println("Example: Read messages from a serial gsm modem.");
//System.out.println(Library.getLibraryDescription());
//System.out.println("Version: " + Library.getLibraryVersion());
// Create the Gateway representing the serial GSM modem.
SerialModemGateway gateway = new SerialModemGateway("modem.com1", "COM4", 115200, "Huawei", "E160");
// Set the modem protocol to PDU (alternative is TEXT). PDU is the default, anyway...
gateway.setProtocol(Protocols.PDU);
// Do we want the Gateway to be used for Inbound messages?
gateway.setInbound(true);
// Do we want the Gateway to be used for Outbound messages?
gateway.setOutbound(true);
// Let SMSLib know which is the SIM PIN.
gateway.setSimPin("0000");
// Set up the notification methods.
Service.getInstance().setInboundMessageNotification(inboundNotification);
Service.getInstance().setCallNotification(callNotification);
Service.getInstance().setGatewayStatusNotification(statusNotification);
Service.getInstance().setOrphanedMessageNotification(orphanedMessageNotification);
// Add the Gateway to the Service object.
Service.getInstance().addGateway(gateway);
// Similarly, you may define as many Gateway objects, representing
// various GSM modems, add them in the Service object and control all of them.
// Start! (i.e. connect to all defined Gateways)
Service.getInstance().startService();
// Printout some general information about the modem.
System.out.println();
System.out.println("Informacion del modem:");
System.out.println(" Fabricante: " + gateway.getManufacturer());
System.out.println(" Modelo: " + gateway.getModel());
System.out.println(" Serial No: " + gateway.getSerialNo());
System.out.println(" SIM IMSI: " + gateway.getImsi());
//System.out.println(" Signal Level: " + gateway.getSignalLevel() + " dBm");
//System.out.println(" Battery Level: " + gateway.getBatteryLevel() + "%");
System.out.println();
// In case you work with encrypted messages, its a good time to declare your keys.
// Create a new AES Key with a known key value.
// Register it in KeyManager in order to keep it active. SMSLib will then automatically
// encrypt / decrypt all messages send to / received from this number.
Service.getInstance().getKeyManager().registerKey("+306948494037", new AESKey(new SecretKeySpec("0011223344556677".getBytes(), "AES")));
// Read Messages. The reading is done via the Service object and
// affects all Gateway objects defined. This can also be more directed to a specific
// Gateway - look the JavaDocs for information on the Service method calls.
ConexionMySQL mysql = new ConexionMySQL();
Connection cnn = mysql.Conectar();
String sms= "";
String remitente="";
//Date fecha;
String sql ="";
int n = 0;
String mensaje="Mensajee satisfactorio";
msgList = new ArrayList<InboundMessage>();
Service.getInstance().readMessages(msgList, MessageClasses.ALL);
for (InboundMessage msg : msgList){
//System.out.println(msg);
sms = msg.getText().toString();
remitente = msg.getOriginator().toString();
//fecha = msg.getDate().getTime();
sql ="INSERT INTO mensaje(mensaje, remitente) VALUES (?,?)";
PreparedStatement post = (PreparedStatement) cnn.prepareStatement(sql);
post.setString(1, sms);
post.setString(2, originator);
n = post.executeUpdate();
if(n >0){
JOptionPane.showMessageDialog(null, mensaje);
Service.getInstance().deleteMessage(msg);
}
// Sleep now. Emulate real world situation and give a chance to the notifications
// methods to be called in the event of message or voice call reception.
System.out.println("Now Sleeping - Hit <enter> to stop service.");
System.in.read();
System.in.read();
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
Service.getInstance().stopService();
}
}
n = post.executeUpdate();
if(n >0){
JOptionPane.showMessageDialog(null, mensaje);
Service.getInstance().deleteMessage(msg);
}
// Sleep now. Emulate real world situation and give a chance to the notifications
// methods to be called in the event of message or voice call reception.
System.out.println("Now Sleeping - Hit <enter> to stop service.");
System.in.read();
System.in.read();
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
Service.getInstance().stopService();
}
}
You should check where you've put the InboundNotification class.
The messages you're seeing from the console with inbound sms comes from there
public class InboundNotification implements IInboundMessageNotification
{
public void process(AGateway gateway, MessageTypes msgType, InboundMessage msg)
{
if (msgType == MessageTypes.INBOUND) System.out.println(">>> New Inbound message detected from Gateway: " + gateway.getGatewayId());
else if (msgType == MessageTypes.STATUSREPORT) System.out.println(">>> New Inbound Status Report message detected from Gateway: " + gateway.getGatewayId());
System.out.println(msg);
}
}
I'm using a Java socket client. In a case where the server is still connected to my client but it does not send a response to my message - I eventually get a read time out exception.
In that case I want to test to see if I should reconnect my socket or just keep it an re-use it.
I use this condition:
if (!socket.isConnected() || socket.isClosed() || !socket.isBound()) {
try {
socket.close();
} catch (IOException e1) {
}
// Wait on a new connection
socket = connectSocket(.....);
}
But I always seem to reconnect. When I log the values of the Boolean properties I see this:
connected: true closed: true bound: true
How can it be connected and closed?
TIA
This thread has some useful discussions on this topic. It turns out that Socket.isConnected returns true if it has (ever) been successfully connected.
From the above thread:
When you use Socket(), which you seem to have overlooked,
Socket.isConnected() tells you whether Socket.connect() has been called
or not. Similarly for isClosed() and close().
Confusion over these methods results from confusing the state of the
socket, which is under the control of the application, with the state
of the overall connection, which is under the control of the protocol.
isConnected() and isClosed() tell what you have done to the socket.
There are no APIs other than read and write for determining the state of
the connection.
The docs says:
Returns true if the socket successfuly connected to a server
and not as one perhaps would expect "returns true if the socket is connected to a server".
The behavior can be confirmed by looking at the source of Socket:
public boolean isConnected() {
// Before 1.3 Sockets were always connected during creation
return connected || oldImpl;
}
You could also run this little test snippet:
Socket s = new Socket();
System.out.println("isConnected: " + s.isConnected() +
" isBound: " + s.isBound() +
" isClosed: " + s.isClosed());
s.connect(new InetSocketAddress("google.com", 80));
System.out.println("isConnected: " + s.isConnected() +
" isBound: " + s.isBound() +
" isClosed: " + s.isClosed());
s.close();
System.out.println("isConnected: " + s.isConnected() +
" isBound: " + s.isBound() +
" isClosed: " + s.isClosed());
Which prints:
isConnected: false isBound: false isClosed: false
isConnected: true isBound: true isClosed: false
isConnected: true isBound: true isClosed: true
I must say that the documentation is quite unclear on this point, and that the method-name is a bit misleading.