Title: Networking: TCP/IP and Basic Sockets
Course: CPS 261: Advanced Java Concepts ~ DL & MM MASTER

Networking: TCP/IP and Basic Sockets

Java Tutorial : Custom Networking - This Url talks about how to work with the Java Networking concepts (this is where I acquired my first knowledge on Java support for Sockets)

Socket Programming

ServerSockets:

Transmission Control Protocol and Internet Protocol:

- TCP/IP is the standard Protocol that almost everything uses.
- A Socket is a data structure or a Class that allows you to communicate with others using TCP/IP. Email, HTTP, FTP, etc. all use Sockets and TCP/IP.
- The concept of Sockets originated With Berkeley Unix with the C Programming language.
- The notion of Sockets has been implemented on many platforms including Java.
- Working with sockets is in many ways similar to an open file. You will be able to communicate with Sockets using classes like Scanner, PrintStream, BufferedReader, ObjectInputStream, ObjectOutputStream, etc.

The system needs to keep track of all of the connections that exist. The following depicts a mechanism used for providing each connection with a unique idenifier:

Java Programming Concepts:

- The ServerSocket class is used by Servers which must bind to a port that is not in use by any other server on the host machine.
- The Socket class is used by Clients to connect to their desired Servers. The Client must know the hostName as either a domain name (myplace.com) or as an IP Address (102.45.67.34)
- The InetAddress class can be used to find the domain name and IP address of the machine you are on.
- The Server task will call the "accept" method to wait for incomming connections
- The accept method returns a Socket when an incomming connection has arrived.
- Both the server task and the client task can call getInputStream() to get an InputStream, and call getOutputStream() to get an OutputStream. Once you have an InputStream and an OutputStream conversation can begin.
- A task can wrap the InputStream with any of your favorite buffering mechanisms: Scanner, BufferedReader, ObjectInputStream, etc.
- A task can wrap the OutputStream with any of your favorite buffering mechanisms: PrintStream, PrintWriter, BufferedWriter, BufferedOutputStream, ObjectOutputStream, etc.
- You must use the appropriate protocol for the Server you chose: Http, Ftp, Telnet, SMTP, EchoServer, RPS, etc.

World's Simplest Protocol: Echo Server

EchoServerSingleThreaded.java (very much brute force)


import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class EchoServerSingleThreaded {

 public static void main(String[] args) throws IOException {
     int portNum = 4444;
     InetAddress iaddr=null;

     ServerSocket serverSocket = null;

     try {
            serverSocket = new ServerSocket(portNum);

            iaddr = InetAddress.getLocalHost();
            System.out.println("Host:" + iaddr.getHostName()+
                 " ipaddr=" + iaddr.getHostAddress()+
                 " portnum="+ portNum);
        }
     catch (IOException e)
        {
            System.err.println("Socket Err:" + e);
            System.exit(1);
        }

     Socket clientSocket = null;

     try{
            clientSocket = serverSocket.accept();
        }
     catch (IOException e) {
            System.err.println("Accept failed." + e);
            System.exit(1);
        }

     PrintStream out = new PrintStream(
                           clientSocket.getOutputStream(), true);


     InputStream is = clientSocket.getInputStream();
     Scanner scanStream = new Scanner(is);


     while (scanStream.hasNextLine()) // Read from socket
       {
             out.println(scanStream.nextLine()); // Echo data read
       }
     out.close();
     scanStream.close();
     clientSocket.close();
     serverSocket.close();
     System.out.println("Exitting ");
    }
}



Note that it is helpful to setup 2 instances of Eclipse for most of these notes.

It's best to run the Server code in one instance of eclipse, and the Client code in another instance of eclipse.
Otherwise, it gets confusing looking at the output from both sides of the conversation.
You will need 2 separate workspaces to simultaneously run 2 eclipses. See the video on this.

Client Sockets:

When we are the Client, we want to use the Socket class instead of the ServerSocket class. The constructor to the Socket class takes an address and a port number. The address can be something like "gettysburg.wccnet.org", or "198.111.176.24".

Also just like before, we can call getOutputStream and getInputStream methods to obtain OutputStream and InputStream classes to communicate with out server.

EchoClient.java

This client can actually be used to talk to more than the Echo Server.
This client will take one line of input and send it to the Server, and then read one line of output and print it to the screen.
This client can be used for other simple protocols like RPS: Rock-Paper-Scissors


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class EchoClient {
    Socket socket=null;

    void communicate(InputStream is, OutputStream os)
    {
        Scanner scanSocket = new Scanner(is);

        PrintStream psSocket = new PrintStream(os, true);

        Scanner keyboard = new Scanner(System.in);

        System.out.println("Start entering text to echo ....");
        String fromKeyboard= keyboard.nextLine();
        while (!fromKeyboard.equals("quit"))
        {
            psSocket.println(fromKeyboard); // write to socket
            String sFromSocket = scanSocket.nextLine(); // read from socket
            System.out.println("received from server: "+sFromSocket);
            fromKeyboard = keyboard.nextLine();
        }
        scanSocket.close();
        psSocket.close();
        keyboard.close();
        System.out.println("Exitting communicate");
    }

public void startup(String[] args){

        String hostName="localhost";
        int portNum=4444;
        InputStream is = null;
        OutputStream os = null;

        if (args.length > 0)
            hostName = args[0];
        if (args.length > 1)
        {
            // An exception can occur here if bad data is entered
            portNum = Integer.parseInt(args[1]);
        }

        try {
            socket = new Socket(hostName, portNum);
            is = socket.getInputStream();
            os = socket.getOutputStream();

            communicate(is,os);

            is.close();
            os.close();
        }
        catch (UnknownHostException e) {
            System.out.println("startup.UnknownHostException: "+e);
        }
        catch (IOException e) {
            System.out.println("startup.IOException: "+e);
        }
        System.out.println("Exitting startup");
    }

    public static void main(String[] args) {


        EchoClient echoClient= new EchoClient();
        echoClient.startup(args);
        System.out.println("Exitting main");

    }

}





Last Modified: September 6, 2015 8:10 PM