Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

Java sockets 101

Roy W. Miller (rmiller@rolemodelsoft.com), Software Developer, RoleModel Software, Inc
Roy Miller is a Software Developer at RoleModel Software, Inc. He has worked to prototype a socket-based application for the TINI Java platform from Dallas Semiconductor. Roy is currently working on porting a COBOL financial transaction system to the Java platform, using sockets. Prior to joining RoleModel, Roy spent six years with Andersen Consulting (now Accenture) developing software and managing projects. He co-authored Extreme Programming Applied: Playing to Win (Addison-Wesley XP Series) scheduled for publication in October 2001.
Adam Williams (awilliams@rolemodelsoft.com), Software Developer, RoleModel Software, Inc
Adam Williams is a Software Developer at RoleModel Software, Inc. He has worked to prototype a socket-based application for the TINI Java platform from Dallas Semiconductor. Roy is currently working on porting a COBOL financial transaction system to the Java platform, using sockets.

Summary:  This tutorial will teach you what sockets are and how to use them in your Java programs. Through several hands-on examples, ranging from single client/sever communication to a pooled collection of clients accessing the server, you will learn how to use sockets to handle typical scenarios that crop up in the real world.

Date:  30 Aug 2001
Level:  Introductory PDF:  A4 and Letter (214 KB | 41 pages)Get Adobe® Reader®

Activity:  23413 views
Comments:  

Appendix

Code listing for URLClient

import java.io.*;
import java.net.*;

public class URLClient {
    protected HttpURLConnection connection;
    public String getDocumentAt(String urlString) {
        StringBuffer document = new StringBuffer();
        try {
            URL url = new URL(urlString);
            URLConnection conn = url.openConnection();
            BufferedReader reader = 
              new BufferedReader(new InputStreamReader(conn.getInputStream()));

            String line = null;
            while ((line = reader.readLine()) != null)
                document.append(line + "\n");

            reader.close();
        } catch (MalformedURLException e) {
            System.out.println("Unable to connect to URL: " + urlString);
        } catch (IOException e) {
            System.out.println("IOException when connecting to URL: " + urlString);
        }

        return document.toString();
    }
    public static void main(String[] args) {
        URLClient client = new URLClient();
        String yahoo = client.getDocumentAt("http://www.yahoo.com");

        System.out.println(yahoo);
    }
}


Code listing for RemoteFileClient

import java.io.*;
import java.net.*;

public class RemoteFileClient {
    protected BufferedReader socketReader;
    protected PrintWriter socketWriter;
    protected String hostIp;
    protected int hostPort;

    public RemoteFileClient(String aHostIp, int aHostPort) {
        hostIp = aHostIp;
        hostPort = aHostPort;
    }
    public String getFile(String fileNameToGet) {
        StringBuffer fileLines = new StringBuffer();

        try {
            socketWriter.println(fileNameToGet);
            socketWriter.flush();

            String line = null;
            while ((line = socketReader.readLine()) != null)
                fileLines.append(line + "\n");
        } catch (IOException e) {
            System.out.println("Error reading from file: " + fileNameToGet);
        }

        return fileLines.toString();
    }
    public static void main(String[] args) {
        RemoteFileClient remoteFileClient = new RemoteFileClient("127.0.0.1", 3000);
        remoteFileClient.setUpConnection();
        String fileContents = 
          remoteFileClient.getFile("C:\\WINNT\\Temp\\RemoteFile.txt");
        remoteFileClient.tearDownConnection();

        System.out.println(fileContents);
    }
    public void setUpConnection() {
        try {
            Socket client = new Socket(hostIp, hostPort);

            socketReader = 
              new BufferedReader(new InputStreamReader(client.getInputStream()));
            socketWriter = new PrintWriter(client.getOutputStream());

        } catch (UnknownHostException e) {
            System.out.println("Error setting up socket connection: 
              unknown host at " + hostIp + ":" + hostPort);
        } catch (IOException e) {
            System.out.println("Error setting up socket connection: " + e);
        }
    }
    public void tearDownConnection() {
        try {
            socketWriter.close();
            socketReader.close();
        } catch (IOException e) {
            System.out.println("Error tearing down socket connection: " + e);
        }
    }
}


Code listing for RemoteFileServer

import java.io.*;
import java.net.*;

public class RemoteFileServer {
    int listenPort;
    public RemoteFileServer(int aListenPort) {
        listenPort = aListenPort;
    }
    public void acceptConnections() {
        try {
            ServerSocket server = new ServerSocket(listenPort);
            Socket incomingConnection = null;
            while (true) {
                incomingConnection = server.accept();
                handleConnection(incomingConnection);
            }
        } catch (BindException e) {
            System.out.println("Unable to bind to port " + listenPort);
        } catch (IOException e) {
            System.out.println("Unable to instantiate a 
              ServerSocket on port: " + listenPort);
        }
    }
    public void handleConnection(Socket incomingConnection) {
        try {
            OutputStream outputToSocket = incomingConnection.getOutputStream();
            InputStream inputFromSocket = incomingConnection.getInputStream();

            BufferedReader streamReader = 
              new BufferedReader(new InputStreamReader(inputFromSocket));

            FileReader fileReader = new FileReader(new File(streamReader.readLine()));

            BufferedReader bufferedFileReader = new BufferedReader(fileReader);
            PrintWriter streamWriter = 
              new PrintWriter(incomingConnection.getOutputStream());
            String line = null;
            while ((line = bufferedFileReader.readLine()) != null) {
                streamWriter.println(line);
            }

            fileReader.close();
            streamWriter.close();
            streamReader.close();
        } catch (Exception e) {
            System.out.println("Error handling a client: " + e);
        }
    }
    public static void main(String[] args) {
        RemoteFileServer server = new RemoteFileServer(3000);
        server.acceptConnections();
    }
}


Code listing for MultithreadedRemoteFileServer

import java.io.*;
import java.net.*;

public class MultithreadedRemoteFileServer {
    protected int listenPort;
    public MultithreadedRemoteFileServer(int aListenPort) {
        listenPort = aListenPort;
    }
    public void acceptConnections() {
        try {
            ServerSocket server = new ServerSocket(listenPort, 5);
            Socket incomingConnection = null;
            while (true) {
                incomingConnection = server.accept();
                handleConnection(incomingConnection);
            }
        } catch (BindException e) {
            System.out.println("Unable to bind to port " + listenPort);
        } catch (IOException e) {
            System.out.println("Unable to instantiate a 
              ServerSocket on port: " + listenPort);
        }
    }
    public void handleConnection(Socket connectionToHandle) {
        new Thread(new ConnectionHandler(connectionToHandle)).start();
    }
    public static void main(String[] args) {
        MultithreadedRemoteFileServer server = 
          new MultithreadedRemoteFileServer(3000);
        server.acceptConnections();
    }
}


Code listing for ConnectionHandler

import java.io.*;
import java.net.*;

public class ConnectionHandler implements Runnable {
    protected Socket socketToHandle;
    public ConnectionHandler(Socket aSocketToHandle) {
        socketToHandle = aSocketToHandle;
    }
    public void run() {
        try {
            PrintWriter streamWriter = 
              new PrintWriter(socketToHandle.getOutputStream());
            BufferedReader streamReader = 
              new BufferedReader(new InputStreamReader(socketToHandle.getInputStream()));
 
            String fileToRead = streamReader.readLine();
            BufferedReader fileReader = 
              new BufferedReader(new FileReader(fileToRead));

            String line = null;
            while ((line = fileReader.readLine()) != null)
                streamWriter.println(line);

            fileReader.close();
            streamWriter.close();
            streamReader.close();
        } catch (Exception e) {
            System.out.println("Error handling a client: " + e);
        }
    }
}


Code listing for PooledRemoteFileServer

import java.io.*;
import java.net.*;
import java.util.*;

public class PooledRemoteFileServer {
    protected int maxConnections;
    protected int listenPort;
    protected ServerSocket serverSocket;
    public PooledRemoteFileServer(int aListenPort, int maxConnections) {
        listenPort = aListenPort;
        this.maxConnections = maxConnections;
    }
    public void acceptConnections() {
        try {
            ServerSocket server = new ServerSocket(listenPort, 5);
            Socket incomingConnection = null;
            while (true) {
                incomingConnection = server.accept();
                handleConnection(incomingConnection);
            }
        } catch (BindException e) {
            System.out.println("Unable to bind to port " + listenPort);
        } catch (IOException e) {
            System.out.println("Unable to instantiate a 
              ServerSocket on port: " + listenPort);
        }
    }
    protected void handleConnection(Socket connectionToHandle) {
        PooledConnectionHandler.processRequest(connectionToHandle);
    }
    public static void main(String[] args) {
        PooledRemoteFileServer server = new PooledRemoteFileServer(3000, 3);
        server.setUpHandlers();
        server.acceptConnections();
    }
    public void setUpHandlers() {
        for (int i = 0; i < maxConnections; i++) {
            PooledConnectionHandler currentHandler =
              new PooledConnectionHandler();
            new Thread(currentHandler, "Handler " + i).start();
        }
    }
}


Code listing for PooledConnectionHandler

import java.io.*;
import java.net.*;
import java.util.*;

public class PooledConnectionHandler implements Runnable {
    protected Socket connection;
    protected static List pool = new LinkedList();
    public PooledConnectionHandler() {
    }
    public void handleConnection() {
        try {
            PrintWriter streamWriter = new PrintWriter(connection.getOutputStream());
            BufferedReader streamReader = 
              new BufferedReader(new InputStreamReader(connection.getInputStream()));

            String fileToRead = streamReader.readLine();
            BufferedReader fileReader = new BufferedReader(new FileReader(fileToRead));

            String line = null;
            while ((line = fileReader.readLine()) != null)
                streamWriter.println(line);

            fileReader.close();
            streamWriter.close();
            streamReader.close();
        } catch (FileNotFoundException e) {
            System.out.println("Could not find requested file on the server.");
        } catch (IOException e) {
            System.out.println("Error handling a client: " + e);
        }
    }
    public static void processRequest(Socket requestToHandle) {
        synchronized (pool) {
            pool.add(pool.size(), requestToHandle);
            pool.notifyAll();
        }
    }
    public void run() {
        while (true) {
            synchronized (pool) {
                while (pool.isEmpty()) {
                    try {
                        pool.wait();
                    } catch (InterruptedException e) {
                        return;
                    }
                }
                connection = (Socket) pool.remove(0);
            }
            handleConnection();
        }
    }
}

9 of 11 | Previous | Next

Comments



static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Java technology
ArticleID=132303
TutorialTitle=Java sockets 101
publish-date=08302001
author1-email=rmiller@rolemodelsoft.com
author1-email-cc=jaloi@us.ibm.com
author2-email=awilliams@rolemodelsoft.com
author2-email-cc=jaloi@us.ibm.com