HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML
 

"Sending Data to a Java Server"
Vol. 1, Issue 2, P.54

	

Listing 1: The DataApplet Code.

// FILE: DataApplet.java
// BY:   Andrew Idsinga 7/28/96

// the imports
import java.io.*;
import java.net.*;
import java.awt.*;
import java.applet.*;

public class DataApplet extends Applet{
	// **init method**
	public void init(){
		//{{INIT_CONTROLS
	  setLayout(null);
	  resize(392,222);
	  name=new TextField(22);
	  add(name);
	  name.reshape(7,33,182,26);
	  title=new TextField(22);
	  add(title);
	  title.reshape(196,33,182,26);
	  label1=new Label("Name:");
	  add(label1);
	  label1.reshape(7,7,182,19);
	  label2=new Label("Title:");
	  add(label2);
	  label2.reshape(203,7,182,19);
	  email=new TextField(22);
	  add(email);
	  email.reshape(7,91,182,26);
	  label3=new Label("Email:");
	  add(label3);
	  label3.reshape(7,65,182,20);
	  sendButton=new Button("Submit Request!");
	  add(sendButton);
	  sendButton.reshape(105,189,182,26);
	  label4=new Label("Telephone:");
	  add(label4);
	  label4.reshape(196,65,182,20);
	  telephone=new TextField(22);
	  add(telephone);
	  telephone.reshape(196,91,182,26);
	  prodinfo=new TextField(44);
	  add(prodinfo);
	  prodinfo.reshape(7,156,371,26);
	  label5=new Label("Product Info. Desired:");
	  add(label5);
	  label5.reshape(7,124,182,26);
	  //}}
	}

	// **class instance variables**
	//{{DECLARE_CONTROLS
	TextField name;
	TextField title;
	Label label1;
	Label label2;
	TextField email;
	Label label3;
	Button sendButton;
	Label label4;
	TextField telephone;
	TextField prodinfo;
	Label label5;
	//}}

	// **class methods**
	public void clickedSendButton() {
		// get the formatted text
		String theData = formatData(name.getText()
			+","+title.getText()+","+
			email.getText()+","+telephone.getText()
			+","+prodinfo.getText());
		// for debugging, display the data
		System.out.println("Data: "+theData);
		// Create and start the DataSender thread
		try{
			showStatus("Creating DataSender object");
			String serv = getDocumentBase().getHost();
			showStatus("Server: "+serv);
			System.out.println("Server: "+serv);
			DataSender ds = new DataSender(
				serv, theData);
			ds.start();
		}
		catch(IOException ioe){
			showStatus("Problem creating DataSender "
				+ioe.toString());
		}
  }

	// handles the "Submit Request" button
	public boolean handleEvent(Event event) {
		if (event.id == Event.ACTION_EVENT
			&& event.target == sendButton) {
			clickedSendButton();
			return true;
		}
		return super.handleEvent(event);
	}

	// this method removes carriage returns from
	// the data and adds a single '\r\n' to the
	// end
	private String formatData(String str){
		StringBuffer sb = new StringBuffer(str);
		for(int x = 0; x < sb.length(); x++){
			if(sb.charAt(x) == '\r'){
				sb.setCharAt(x, '\040');
				if(sb.charAt((x+1)) == '\n'){
					sb.setCharAt((x+1), '\040');
				}
			}
		}
		// set the terminating '\r\n'
		sb = sb.append('\r');
		sb = sb.append('\n');
		String retData = new String(sb);
		return retData;
	}
}

Listing 2: DataReceiver.java

// FILE: DataReceiver.java
// BY:   Andrew Idsinga 7/28/96

// the imports
import java.io.*;
import java.net.*;

public class DataReceiver extends Thread{
	// **main method**
	public static void main(String args[]){
		System.out.println("Starting DataReciever");
		System.out.println("Current log file: "
			+FILENAME);
		// create the ServerSocket object
		ServerSocket ss = null;
		try{
			 System.out.println(
			 	"Creating ServerSocket");
			 ss = new ServerSocket(USE_PORT);
		}
		catch(IOException ioe){
			System.out.println("Could not create"
				+" ServerSocket ss"+ioe.toString());
			System.exit(1);
		}
		// loop waiting for inbound connections
		try{
			while(true){
				Socket s = ss.accept();
				System.out.println(
					"Connection from: "+
					s.getInetAddress().toString());
				// create and start a DataReceiver
				// thread to accept incoming data
				DataReceiver dr = new DataReceiver(
					s, FILENAME);
				dr.start();
			}
		}
		catch(IOException ioe){
			System.out.println("Problem in accept loop"
				+ioe.toString());
		}
	}

	// **class constant variables**
	// the port to be used for incoming connections
	private static final int		USE_PORT = 6969;
	// the system dependant filename which data
	// will be written to
	private static final String	FILENAME =
		".\\dataread.log";

	// **class instance variables**
	// the Socket object used for communications
	Socket s;
	// The file to be written to
	String fileName;
	// input streams for reading from the Socket
	DataInputStream dis;

	// **class constructor**
	public DataReceiver(Socket theSock,
		String theFileName){

		fileName = theFileName;
		s = theSock;
		try{
			dis = new DataInputStream(
									s.getInputStream());
		}
		catch(IOException ioe){
			System.out.println(ioe.toString());
		}
	}

	// **the thread's run method**
	public void run(){
		try{
			// read and write the data
			String readStr = dis.readLine();
			writeData(readStr);
			// close the iinput streams and the socket
			dis.close();
			s.close();
		}
		catch(IOException ioe){
			System.out.println("Problem reading"
			+" from Socket s "+ioe.toString());
			return;
		}
	}

	// **class methods**
	// this method os called from the run() method
	// to write the data to the file
	private synchronized void writeData(
		String data){

		try{
			// open the file for writing
			RandomAccessFile file =
				new RandomAccessFile(FILENAME, "rw");
			// seek to the end of the file
			file.seek(file.length());

			// write the data
			file.writeBytes(data);
			// write a '\r\n' (for dos editors)
			file.writeByte('\r');
			file.writeByte('\n');
			// close the file
			file.close();
		}
		catch(IOException ioe){
			System.out.println("Problems writing, "+
				ioe.toString());
		}

		System.out.println("Press CTRL-C "+
			"to quit DataReciever");
		return;
	}
}

Listing 3: DataSender.java

// FILE: DataSender.java
// BY:   Andrew Idsinga

// the imports
import java.io.*;
import java.net.*;

public class DataSender extends Thread{
	// **the thread's run method**
	public void run(){
		System.out.println("DataSender, run()");
		try{
			dos.writeBytes(theData);
			// close the output stream and the socket
			dos.close();
			clntSock.close();
		}
		catch(IOException ioe){
			System.out.println(ioe.toString());
			return;
		}
	}

	// **class constant variables**
	// the same port that is used on the server
	private static final int USE_PORT = 6969;

	// **class instance variables**
	Socket clntSock;
	String servStr;
	String theData;
	DataOutputStream dos;

	// **class constructor(s)**
	public DataSender(String theServer,
		String data)throws IOException{
		// for debugging, display some data
		System.out.println(
			"DataSender, constructor");
		// assign local references
		servStr = theServer;
		theData = data;

		// create and connect the socket
		// to the server
		//       (the server name, the port to use)
		clntSock = new Socket(servStr, USE_PORT);

		// get the output stream so we can write
		// data to the socket
		dos = new DataOutputStream(
			clntSock.getOutputStream());
	}
}

Listing 4: The DataApplet HTML.

<html>
<body>

<applet code="DataApplet.class" width=392 height=222>
You must have a Java enabled browser for DataApplet!
</applet>

</body>
</html>


 

All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.