Here's the source code for a Java class I put together quickly from a number of other sources on the internet. In short, this class connects to a port on a remote server, sends a command to that server to be executed, and then reads the output from the command that is executed.
This Java code works as a client, and calls a Ruby script I've installed on several remote servers. That script runs under xinetd on the remote Linux systems, executes the commands I pass to it, and returns the results to me.
Although I've hard-coded a number of variables in this Java class, I think you'll be able to modify it very easily to work for your needs when it comes to open and connect to remote sockets.
Without any further introduction, here is the source code for my Java SocketClient class:
import java.io.*;
import java.net.*;
public class SocketClient
{
Socket sock;
String server = "ftpserver";
int port = 5550;
String filename = "/foo/bar/application1.log";
String command = "tail -50 " + filename + "\n";
public static void main(String[] args)
{
new SocketClient();
}
public SocketClient()
{
openSocket();
try
{
// write to socket
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
wr.write(command);
wr.flush();
// read from socket
BufferedReader rd = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String str;
while ((str = rd.readLine()) != null)
{
System.out.println(str);
}
rd.close();
}
catch (IOException e)
{
System.err.println(e);
}
}
private void openSocket()
{
// open a socket and connect with a timeout limit
try
{
InetAddress addr = InetAddress.getByName(server);
SocketAddress sockaddr = new InetSocketAddress(addr, port);
sock = new Socket();
// this method will block for the defined number of milliseconds
int timeout = 2000;
sock.connect(sockaddr, timeout);
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (SocketTimeoutException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Post new comment