CPU ram and free space for remote servers java - java

I want to get CPU ram free space with java for many server
any idea.

Well depending on target platform there are multiple ways:
Have java clients running on each system that will collect this information on request and then have a server that collect and display all this information. This is most platform independent solution but require you to write client and server and install clients on each system.
If SSH is supported on platforms, you can using Java program to login to each system and use command line utilities to query resource. This however require you to either have credentials for each system or the SSH keys available.
Use NET-SNMP on target platforms if supported and enable resource collection. Java program can then query the SNMP agent to collect resource usage. You would require a library to talk with SNMP agents. You can SNMP4J or AdventNet for this purpose.

Im just a Trainee but my solution would be to Write a Server socket and run it on the servers.
Than open a connection over a Client socket and ask for information.
Than i would simpel return the Used Mb or simple convert it to a % Value.
Anyway i would prefer to use a existing and tested solution.
EDIT:
Here a Tutorial on how to get your free , Max and Used RAM.
http://crunchify.com/java-runtime-get-free-used-and-total-memory-in-java/
EDIT2:
Here the code of my Idear:
Server Part:
public static void main(String[] args) {
try {
ServerSocket sSocket = new ServerSocket(6969);
Socket socket = sSocket.accept();
DataInputStream dis = new DataInputStream(socket.getInputStream());
DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
String str1 = "";
//Add Varaibles you want to return
double ram = 15.0;
while (!str1.equals("stop")) {
str1=dis.readUTF();
//Return Value you need by param
if (str1.equals("getRam")) {
//Add Your calculation here
dout.writeUTF(String.valueOf(ram));
dout.flush();
}
else if(str1.equals("stop")){
dout.writeUTF("stop");
dout.flush();
}
else {
dout.writeUTF("Unknown Command");
dout.flush();
}
}
sSocket.close();
socket.close();
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client part:
public class Main {
public static void main(String[] args) {
try {
String serverIp = "localhost";
Socket socket = new Socket(serverIp, 6969);
DataInputStream dIn = new DataInputStream(socket.getInputStream());
DataOutputStream dOut= new DataOutputStream(socket.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = "";
String str2 = "";
dOut.writeUTF("getRam");
//for manual param transmitting
//str = br.readLine();
//dOut.writeUTF(str);
dOut.flush();
str2=dIn.readUTF();
System.out.println("Server response:" + str2);
br.readLine();
} catch (UnknownHostException e) {
e.printStackTrace();
System.out.println(e);
} catch (IOException e) {
e.printStackTrace();
System.out.println(e);
}
}
}
I hope that helps you.
Anyway i dont think you can get data without connecting or have a connection to your server.

Related

Android socket wait issue

Hello I have an app that connect to a remote server using sockets
socket = new Socket();
socket.connect(new InetSocketAddress(Ip, portNum), 7000);
I have 2 methods send & receive
the scenario in send is
PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
in method receive
String msg = "";
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (in.ready()) {
msg = msg + (char) in.read();
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
in AsyncTask of a different class I call
send();
String response=receive();
The above code is not sending or receiving without a wait period
i.e
Thread.sleep(2000);
I know sleep is a bad approach
what is the best scenario should I use?
Is it better to make an AsyncTask within send method and another one for receive method.
Here is where I use sleep and what data send & receive
client.send(some sql statement representED as json format);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// sql select result represented as json
String RESULT = client.recive();
Likely your server is not listening before you try to connect. Though this is unclear from the code you have posted. You'll need to show both server and client code there.

My java chat client only sends strings when the dataStream is closed

I created a java chat application (client and server)
Everything works fine when I'm on my LAN (using LAN IP address of the server into my client).
But when I'm using the Internet address of my server in my client, the strings are sent only when I close the output Data stream of my client (and all the strings are sent at once).
Here's a quick snap of my code (I have port forward from 6791 to 6790 in the example below),
My server (thread):
// this line is actually on my global server class, used below with theServer
ServerSocket svrSocket= new ServerSocket(6790);
//wait for incoming connection
connectionSocket = svrSocket.accept();
connectionSocket.setSoTimeout(10000);
// free the accepting port
svrSocket.close();
//create a new thread to accept future connections (creates a new svrSocket)
theServer.openNewConnection();
//create input stream
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
boolean threadRunning = true);
while (threadRunning) {
//System.out.println("thread: in the while");
try {
Thread.sleep(100);
clientSentence = inFromClient.readLine();
System.out.println(clientSentence);
}
catch...
}
My client:
InetAddress dnsName;
Socket clientSocket;
PrintWriter out;
dnsName = InetAddress.getByName("myAddress.me");
clientSocket = new Socket(dnsName.getHostAddress(), 6791);
Thread.sleep(10);
out = new PrintWriter(clientSocket.getOutputStream(), true );
int i=140;
while (i>130){
try {
out.println(Integer.toString(i));
out.flush();
Thread.sleep(200);
}
catch(Exception e) {
e.printStackTrace();
}
i--;
}
out.flush();
out.close();
clientSocket.close();
I've tried with DataOutStreams, there's nothing to do.
My server will only receive the strings when out.close() is called on client side.
Is there a reason why, over the Internet, the data stream has to be closed for data to be sent? Is there a way around this? Am I doing something wrong?

Android java How to connect to server with different network/ip address

How to connect to server with different IP address
I really don't know what to do...
Let me explain first.
i have a client and server that works great when sending messages between the two if i am on the same network as my computer.
i have an android device and i would like to wish when ever i am placed far away and when i will click some button it will send message to server even if i am not on the same network.
Client
try {
client = new Socket("IpAddress", 4444);
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
printlng = new PrintWriter(client.getOutputStream());
printlng.println(mlng);
printlng.flush();
while (true) {
if ((Response= in.readLine()) != null) {
Log.i("Response:", Response);
dlng = Double.valueOf(Response);
System.out.println(dlng);
break;
}
}
Server:
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(4444); // Server socket
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
}
System.out.println("Server started. Listening to the port 4444");
while (true) {
try {
clientSocket = serverSocket.accept(); // accept the client
inputStreamReader = new InputStreamReader(
clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); // get
// the
// client
PrintWriter out = new PrintWriter(
clientSocket.getOutputStream(), true);
InputStream inputStream = new ByteArrayInputStream(
bufferedReader.readLine().getBytes(
Charset.forName("UTF-8")));
BufferedReader bufferedReader2 = new BufferedReader(
new InputStreamReader(inputStream));
String output = bufferedReader2.readLine();
System.out.println(output.toString());
out.println(output.toString());
out.flush();
out.close();
inputStreamReader.close();
clientSocket.close();
} catch (IOException ex) {
System.out.println("Problem in message reading");
}
}
}
You have to find out the external/internet ip address of the pc where your server is running on. You can do that on that pc with http://whatismyip.com. Use the obtained ip in your client. But before it really can work you have to configure the router where your pc is connected to to forward the used port to the lan ip address of your pc.
If everything works fine when you are on the same LAN : the problem is probably coming from some firewall rule not accepting connection on port 4444 when coming from a non local IP.
So, either change the port of the server (if not used yet, port 80 is probably a good choice since there is more chance that connections will be allowed), either change your firewall rules.

Streaming data through sockets continuously in java

I wanted to send/receive continuous stream of data from one endpoint to another(peer2peer) with push and pull 'able asynchronously
So to first solve communication , I started with jax-ws soap binding webservice since it has an endpoint and ws-addressing for push mechanism but it seems to be a lot of overhead (heavy as per the docs and since unfamiliar with ws-*, I haven't implemented it , as I need multiple clients listening to the stream at a later point and the stream is 24/7 I wanted thread manageable sockets).
Then I took jax-rs but it does not include ws-addressing in it.(jax-rs 2.0)
I also looked at websockets but it required an app server but I want a jvm supportable code
So, Now I am trying to use basic sockets but the problem I am having is streaming the data through socket at server and client receiving it continuously.
It is working for the first read but no further.
Secondly, how can I make it asynchronous?
public class sSocket {
public static void main(String args[]) throws IOException{
int i = 15000;
ServerSocket ss;
Socket socket = null;
ss = new ServerSocket(i);
try
{
socket = ss.accept();
socket.setKeepAlive(true);
int iii = 0;
System.out.println("New connection accepted " + socket.getInetAddress() + ":" + socket.getPort());
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
while(iii<9)
{
Thread.sleep(2000);
output.write("good" + iii + "\n");
//System.out.print(input.readLine().toString());
output.flush();
iii++;
}
//socket.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
public class cSocket {
public static void main(String args[]) throws InterruptedException, IOException{
Socket client = new Socket("127.0.0.1", 15000);
try{
client.setKeepAlive(true);
DataOutputStream out = new DataOutputStream(client.getOutputStream());
out.writeBytes("Hi Server! I'm " + client.getLocalSocketAddress() + "\n" );
BufferedReader input = new BufferedReader(new InputStreamReader(client.getInputStream()));
String s;
while(true){
if((s = input.readLine()) != null)
{
System.out.println("Message from Server: " + s);
}}
//client.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
[toString() unavailable - no suspended threads] I see this halting the code in eclipse.
The problem seems to be essentially rooted in the input.readLine() in client: error is connection reset : which I assume is because readLine() has reached "EOF"
Don't keep creating new streams. Use the same ones for the life of the socket, at both ends. You're losing data in the buffers.
You don't need to keep calling setKeepalive(). Once is enough.

buffered reader not receiving data from socket

I am writing a client application that will receive a continuous flow of data through tcp/ip. The problem I'm having is that the buffered reader object isn't receiving any data and is hanging at the readline method.
The way the server works is that you connect to it, and then send authentication information in order to receive data. The gist of my code is below
socket = new Socket(strHost, port);
authenticate();
inStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
process(inStream);
authenticate()
{
PrintWriter pwriter = new PrintWriter(socket.getOutputStream(), true);
pwriter.println(authString);
}
process(BufferedReader bufferedReader)
{
while((line = bufferedReader.readLine()) != null)
dostuff
}
I created a sample server application that sends data the way (I think) the server is sending data and it connects, and receives and processes the data fine. I can connect to the server fine in my application. I can also telnet to the server and write the authentication string and receive a flood of data using telnet. However my application just hangs at readLine with the server and I'm out of idea's why.
The data coming in (through telnet atleast) looks like a continuous stream of the following:
data;data;data;data;data
data;data;data;data;data
Why is my app hanging at readline, am I not outputting the authentication line correctly? I'm not receiving any errors...
EDIT
My sample server code (which is working correctly)...again this is only mimicking the way I think the real server is running but I can connect to both in my application just not receive data from the real server.
public static void main(String[] args) throws IOException
{
ServerSocket serverSocket = null;
try
{
serverSocket = new ServerSocket(1987);
}
catch (IOException e)
{
System.out.println("Couldn't listen on port: 1987");
System.exit(-1);
}
Socket clientSocket = null;
try
{
clientSocket = serverSocket.accept();
}
catch (IOException e) {
System.out.println("Accept failed: 1987");
System.exit(-1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String something;
while ((something = in.readLine()) != null)
{
while(true)
{
out.println(message);
}
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
Firstly you should call BufferedReader.ready() before calling readLine(), as the ready() will tell you if it's ok to read.
PrintWriter doesn't throw I/O Exception so the write may have failed without your knowledge which is why there is nothing to read. Use PrintWriter.checkError() to see if anything as gone wrong during the write.
You ought to set up the input and output streams on the Socket at the same time before you write anything down the pipe. If your reader is not ready when the other end tries to write you will get a broken pipe in the server and it won't send any more data. Telnet sets up read and write before you have written or read anything.
You can make use of Wireshark to tell if the server is actually sending data.
BufferdReader.readLine() reads lines, i.e. sequences of characters ended with \r or \r\n. I guess that your server writes its output into one single line. Your telnet output proves this assumption. Just use PrintWriter.println() at server side.
this work with me
with socket without flush
void start_listen()
{
String result1="";
char[] incoming = new char[1024];
while (!s.isClosed())
{
try {
int lenght = input.read(incoming);
result1 = String.copyValueOf(incoming,0,lenght);
}
catch (IOException e)
{
e.printStackTrace();
}
Log.d("ddddddddddd",result1);
}

Categories