Blame | Last modification | View Log | RSS feed
package heizung;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
public class network
{
private boolean DEBUG = false;
private Socket s = null;
private PrintWriter out = null;
private BufferedReader in = null;
private String strServerName = "localhost";
private int online = 0;
public network(String sn)
{
if (!sn.isEmpty())
strServerName = sn;
online = 0;
}
public boolean connect()
{
try {
online = 2;
s = new Socket(strServerName, 11001);
s.setSoTimeout(3000);
out = new PrintWriter(s.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(s.getInputStream()));
}
catch (UnknownHostException e)
{
System.err.println("Don't know about host: "+strServerName+": "+e.getMessage());
online = 0;
return false;
}
catch (SocketTimeoutException e)
{
System.err.println("Could't set timeout: "+e.getMessage());
online = 0;
return false;
}
catch (IOException e)
{
System.err.println("Couldn't get I/O for the connection to: "+strServerName+": "+e.getMessage());
online = 0;
return false;
}
// Just wait a little to let daemon initialize
try
{
Thread.sleep(500);
}
catch (InterruptedException e1)
{
System.out.println("Error: "+e1.getMessage());
}
online = 1;
return true;
}
public int write(String str)
{
if (online == 1 && !str.isEmpty())
{
out.print(str);
out.flush();
}
if (online != 1)
{
System.err.println("There is no valid network connection!");
return 0;
}
return str.length();
}
public String read()
{
char[] ch;
String answer = "";
if (online != 1)
{
System.err.println("There is no valid network connection!");
return "";
}
ch = new char[2];
try
{
while (in.read(ch, 0, 1) != -1)
{
if (ch[0] == ';')
{
if (DEBUG)
System.out.println("Found answer:"+answer);
return answer;
}
answer = answer+ch[0];
}
}
catch (SocketTimeoutException e)
{
System.err.println("Error: "+e.getMessage());
}
catch (IOException e)
{
System.err.println("Error reading from stream: "+e.getMessage());
}
return "";
}
public void close()
{
if (online != 1)
return;
out.print("quit;");
out.close();
try
{
in.close();
s.close();
}
catch (IOException e)
{
System.err.println("Error closing a socket: "+e.getMessage());
}
}
}