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

"Socket Programming With Java"
Vol. 2, Issue 4, p. 54


Listing 1: Create a Socket Object

		ourSocket = new Socket(serverName, 80);
	}catch(UnknownHostException e){
		//..code if the host does not exist
	}catch(IOException e){
		System.out.println(" Unable to open the Socket to "+serverName);

Listing 2: Establish input and output streams.

		ourInputStream = ourSocket.getInputStream();
		ourOutputStream = ourSocket.getOutputStream();
	}catch(IOException e){
		System.out.println("unable to open streams");

Listing 3: Closing the socket.

	}catch(IOException e){
		System.out.println("Exception thrown closing the Socket");

Listing 4

public class SocketClient extends Frame implements Runnable{
    /* *******   Data Section    ******** */
    TextField theServer,theFile;
    TextArea theHTMLCode;
    Thread thread;
    Button search, stopSearch;
    Socket ourSocket;

    * This is the default constructor for this class. Its job is to initialize
    * the SocketClient object. We construct a Frame Window here. A data entry
    * panel is created and added "North". Here a user will be able to enter a server
    * name and a file to retrieve. If no file name is specified, index.html will be the
    * default file to search for.
    public SocketClient(){

        setTitle("Socket Client Example");   
//Set the frame window title.
        setLayout(new BorderLayout());       
//Set the layout for the window.
        theServer = new TextField("www.",20);
//Create the data entry fields.
        theFile = new TextField("",20);
        theHTMLCode = new TextArea("",25,100);
//Make the TextArea not editable.

        Panel pan = new Panel();             
//Make a panel to contain the data
        pan.setLayout(new FlowLayout());     
//  entry fields and set the layout.
        pan.add(new Label("http://"));       
//Add text labels to the panel as
//  well as the Data Entry Objects.
        pan.add(new Label("/"));
        search= new Button("Get the file");
        stopSearch= new Button("Stop");


//Add the panel North.
//Add the TextArea Center.

        thread = new Thread(this);          
//Create a new thread.
//Resize the Window to an appropriate size.
//Display the Window.

Listing 5: HandleEvent Method.

    * This is the handleEvent method. We provide code for the events triggered
    * from a user pressing a button or destroying the window (Exiting the program).
    * @param Event e
    * @see event
    public boolean handleEvent(Event e){
        if(e.target == search){         
//If the Search Button was pressed, do this.
//If no file was specified
//  set the file name to index.html.
            theHTMLCode.setText("Looking Up Server: "+theServer.getText());
            thread = new Thread(this);
//This calls the run() method for this.
            return true;
        if(e.target == stopSearch){     
//If the Stop Button was pressed, do this.
            theHTMLCode.setText("Operation aborted by user");
            return true;
        if(e.id ==Event.WINDOW_DESTROY){    
//If the user wants to exit the program.
//Notice how we do not need to return here.
        return super.handleEvent(e);        
//If we do not handle the event, pass it up the chain.

Listing 6: Run Method

    * This is the run method. It will open a socket connection to a web server and then
    * get the input and output streams.  Then we will simulate the way a web browser
    * asks the server for a file with the GET statement. After that, we  will read the
    * text data from the web server.
    public void run(){
        //Get the Socket and Streams
            ourSocket = new Socket(theServer.getText(),80);
            DataInputStream inStream   
//Notice how we kill a few birds with one stone.
                    = new DataInputStream(ourSocket.getInputStream());
            DataOutputStream outStream 
//Here too!
                    = new DataOutputStream(ourSocket.getOutputStream());

Listing 7: File Request String.

          /* Here we construct a file request string.  Since we are using
             * a HTTP server, we need to simulate a file request. We do this
             * like: GET /filename HTTP/1.0\r\n\r\n
             * Notice that two  ctrl/lf sequences are needed at the end of the request
            String requestString ="GET /"+ theFile.getText()+" HTTP/1.0\r\n"+ "\r\n";
            theHTMLCode.appendText("\n The Request String is:\n"+requestString);
//Send the Request to the HTTP server
//Don't forget to flush the stream.
            theHTMLCode.appendText("\n ....Asking for file:"+theFile.getText());

        //Read the file until EOF.
            StringBuffer buff = new StringBuffer();
            String currLine;
            while((currLine = inStream.readLine())!=null){
                buff.append(currLine + "\n");
//Place the text into the Text Area.

        //Close the Socket

        catch(Exception e){  /* Since several exceptions can be thrown, We can catch all of them
                              * with the base class for Exceptions.
            theHTMLCode.setText("Exception with: "+e.getMessage()+"\n"+e.toString());

Listing 8: Main Method.

    /** This is the main method. Program execution begins here
    public static void main(String[] args){
        new SocketClient();



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.