When i run my code it's working fine but after some hours it stop working and show this error Not able to publish: MQTT client is not connected
public Mqtt5AsyncClient connect(String host, int port) {
Mqtt5AsyncClient client = MqttClient.builder().useMqttVersion5()
.identifier(UUID.randomUUID().toString())
.serverHost(host)
.serverPort(port).buildAsync();
Mqtt5ConnAck connectionAck = null;
try {
connectionAck = client.toBlocking().connect();
Mqtt5ConnAckReasonCode connAckCode = connectionAck.getReasonCode();
logger.debug("Client connected to broker with url: " + host + ":" + port + " ::Connection ack code: " + " keep alive ");
} catch (Exception ex) {
logger.debug("Not able to connect to broker with url: " + host + ":" + port);
ex.printStackTrace();
}
return client;
}
Related
I've created program to send and get data from client to server and for client i used java and server I used Visual Basic so how to set the connection between client and server is keep alive in a client(java) side?
this is the code from client :
public static void Client(){
String print = "";
String dataDB = "Hello server, From Client";
try(Socket clientSocket = new Socket("localhost", port)){
clientSocket.getOutputStream().write(dataDB.getBytes("ASCII"));
while (clientSocket.getInputStream().available() == 0) {
Thread.sleep(100L);
}
byte[] data = new byte[clientSocket.getInputStream().available()];
int bytes = clientSocket.getInputStream().read(data, 0, data.length);
print = new String(data, 0, bytes, "ASCII");//.substring(4,bytes);
while(print.length()>0){
System.out.println("From Server : "+print);
}
}catch (IOException ex){
System.out.println("I/O error: " + ex.getMessage());
}catch(InterruptedException ie){
System.out.println("error: " + ie.getMessage());
}catch(Exception e){
System.out.println("error: " + e.getMessage());
}
}
The Java client is a console application, just sent and get data from server i tried to used clientSocket.setKeepAlive(true); but is not working.
So I have this Javascript server:
const net = require('net');
var port = process.env.PORT || 3001;
net.createServer(function (sock){
console.log('CONNECTED: ' + sock.remoteAddress + ":" + sock.remotePort);
sock.on('data', function(data){
console.log(data.toString());
});
sock.on('close', function(data){
console.log('DISCONNECTED: ' + sock.remoteAddress + ":" + sock.remotePort);
});
sock.on('error', function(error){
console.log(error);
});
}).listen(port, '0.0.0.0');
console.log('Listening on: ' + port);
And I use this to connect my Java client:
public void connect () {
System.out.println("Connecting with: " + host + ":" + port);
try {
this.socket = new Socket(this.host, this.port);
System.out.println("Connected!");
} catch (IOException e) {
e.printStackTrace();
}
}
And it works when I try it local but whenever I upload it to heroku it never logs a CONNECTED message or any received data so I don't think it connects.
I'm using this as ip/port to connect my client: .herokuapp.com:heroku.env.PORT not literally ofcourse, I use the port heroku gives to my application on launch since I do see the Listening on: message.
Am I doing something wrong? Or does heroku not support sockets?
Your client should connect to <appname>.herokuapp.com on port 80 or 443. The PORT var is for internal binding only.
Below is the code I will run to spawn a server on my localhost.
However I want 3 instances of server code to run on ports 5000, 6000, 7000.
I can think of creating 3 .java files each hard coded with different port number.
But is there a better way to spawn 3 server instances on localhost without cut copy pasting 3 files ?
public void startServer() {
try {
ServerSocket welcomeSocket = new ServerSocket(5000);
while (true) {
// Create the Client Socket
Socket clientSocket = welcomeSocket.accept();
ObjectInputStream inFromClient = new ObjectInputStream(clientSocket.getInputStream());
Message m = (Message) inFromClient.readObject();
System.out.println("---- hello: my message is: " + m.name);
}
} catch (Exception e) {
System.err.println("Server Error: " + e.getMessage());
System.err.println("Localized: " + e.getLocalizedMessage());
System.err.println("Stack Trace: " + e.getStackTrace());
System.err.println("To String: " + e.toString());
}
}
You can do this:
public void startServer(int port) {
try {
ServerSocket welcomeSocket = new ServerSocket(port);
while (true) {
// Create the Client Socket
Socket clientSocket = welcomeSocket.accept();
ObjectInputStream inFromClient = new ObjectInputStream(clientSocket.getInputStream());
Message m = (Message) inFromClient.readObject();
System.out.println("---- hello: my message is: " + m.name);
}
} catch (Exception e) {
System.err.println("Server Error: " + e.getMessage());
System.err.println("Localized: " + e.getLocalizedMessage());
System.err.println("Stack Trace: " + e.getStackTrace());
System.err.println("To String: " + e.toString());
}
}
And now, just call:
startServer(5000);
startServer(6000);
startServer(7000);
Or, even better: use a loop to start the servers three times.
Port 161 is used by SNMP. I wrote a small peice of code to check if a device is running SNMP on this port.
public boolean isPortOpen(String ip, int port, int timeout) {
try {
Socket socket = new Socket();
socket.connect(new InetSocketAddress(ip, port), timeout);
socket.close();
logger.info(threadId, "Port is Open : " + ip + ":" + port );
return true;
} catch (IOException ex) {
logger.error(threadId, "isPortOpen : " + ip + ":" + port + "\t"+ ex.getMessage());
return false;
}
}
However to my surprise the code always returns false for port 161 even though the box is running SNMP and other tools such as PortQryV2 return true for port 161. Can someone please help!! TIA
I am Working on TCP/IP in Java. First, I read TCP/IP and understand how it's working.
What i Need:-
Ok, Now i want to implement it in java. I am trying to Send some input in request to specific port/IP from my IP. and need to get response.
I don't understand how to implement it.
Here is my Input:
Destination IP
Destination Port
Input(String or Anything)
Here is my code which i use for Client.
try {
socket = new Socket("localhost", port);
}
catch(Exception e) {
System.out.println("Error connectiong to server:" + e);
return;
}
System.out.println("Connection accepted " +
socket.getInetAddress() + ":" +
socket.getPort());
/* Creating both Data Stream */
try
{
Sinput = new ObjectInputStream(socket.getInputStream());
Soutput = new ObjectOutputStream(socket.getOutputStream());
}
catch (IOException e) {
System.out.println("Exception creating new Input/output Streams: " + e);
return;
}
// now that I have my connection
String test = "aBcDeFgHiJkLmNoPqRsTuVwXyZ";
// send the string to the server
System.out.println("Client sending \"" + test + "\" to serveur");
try {
Soutput.writeObject(test);
Soutput.flush();
}
catch(IOException e) {
System.out.println("Error writting to the socket: " + e);
return;
}
// read back the answer from the server
String response;
try {
response = (String) Sinput.readObject();
System.out.println("Read back from server: " + response);
}
catch(Exception e) {
System.out.println("Problem reading back from server: " + e);
}
try{
Sinput.close();
Soutput.close();
}
Please give me some hint or reference.
Creating Scoket
go through this will help you.
if you are implementing Sockets, you need to use ServerSocket class to create the ServerSocket . Then Socket class to request the create the connection between Client and Sever.