Monday, July 20, 2009

Java HTML writer

import java.io.*;import java.net.*;
import java.applet.Applet;import netscape.javascript.JSObject;
public class HTMLWriter extends Writer

{
JSObject main_window;
JSObject window;
JSObject document;
static int window_num = 0;
public HTMLWriter(Applet applet, int width, int height)

{
try { Class c = Class.forName("javascript.JSObject");

}
catch (ClassNotFoundException e)
{
throw new NoClassDefFoundError("error");
}
main_window = JSObject.getWindow(applet);
window = (JSObject) main_window.eval("self.open(''," +"'HTMLWriter" + window_num++ + "'," + "'menubar,status,resizable,scrollbars," +"width=" + width + ",height=" + height + "')");
document = (JSObject) window.getMember("document");

document.call("open", null);
}
public void write(char[] buf, int offset, int length)

{
if ((window == null) (document == null)) return;
if (((Boolean)window.getMember("closed")).booleanValue()) return;
String s = new String(buf, offset, length);
document.call("write", new String[] { s });

}
public void flush() {}
public void close() { document.call("close", null); document = null;

}
public void closeWindow()

{
if (document != null) close();
if (!((Boolean)window.getMember("closed")).booleanValue()) window.call("close", null); window = null;
}
public void finalize()

{
closeWindow();
}
public static class Test extends Applet

{
HTMLWriter out;
public void init()

{
try
{
URL url = new URL(this.getDocumentBase(), this.getParameter("url"));
Reader in = new InputStreamReader(url.openStream());
out = new HTMLWriter(this, 400, 200);
char[] buffer = new char[4096];

int numchars;
while((numchars = in.read(buffer)) != -1) out.write(buffer, 0, numchars);
in.close();

out.close();
}
catch (IOException e)
{}
}
public void destroy()

{ out.closeWindow();
}
}
}

Sunday, July 12, 2009

java TCP client

import java.io.*;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
public class TCPClient {
public static void main(String srgd[]) {
try {
InetAddress serverAddr = InetAddress.getByName("localhost");
System.out.println("TCP"+ "C: Connecting...");
Socket socket = new Socket(serverAddr, 8080);
String message = "Hello from Client";
try {
System.out.println("TCP"+ "C: Sending: '" + message + "'");
PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
out.println(message);
System.out.println("TCP"+ "C: Sent.");
System.out.println("TCP"+ "C: Done.");
BufferedReader bf=new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str;
while(!(str= bf.readLine()).equals("")) {
System.out.println("TCP"+"C: Recieve "+str);
}
} catch(Exception e) { System.out.println("TCP"+ "S: Error"+ e); }
finally {
socket.close();
}
} catch (Exception e) {
System.out.println("TCP"+ "C: Error"+ e);
}
}
}