TCP Sockets Lecture Notes

TCP Sockets in Client-Server Applications

  • Client-server applications involve a server providing services and a client utilizing those services.

  • Communication must be reliable, ensuring:

    • No data drops

    • Ordered delivery of data from server to client

  • TCP provides a reliable communication channel between client and server.

  • Establishing communication requires both parties to connect:

    • Each program binds a socket to its end of the connection.

    • They communicate by reading from and writing to the socket.

TCP Sockets: Definitions

  • Socket: An endpoint for a two-way communication between programs running on the network.

  • Endpoint: Combination of an IP address and a port number.

  • Unique identification of TCP connections by their two endpoints.

Ports: A Reminder

  • Networking with Ports:

    • A computer typically has a single physical connection to the network.

    • Data destined for a computer may be for different applications.

    • Ports help identify the application for data forwarding.

TCP Sockets in Java

  • The java.net package provides:

    • Socket Class: Client-side connection implementation.

    • ServerSocket Class: Server-side connection implementation.

TCP Sockets: Client vs. Server

  • Servers run on specific computers with a server socket bound to a specific port.

  • Servers listen for connection requests from clients.

  • Clients must know the server hostname and the listening port number.

  • Connection process:

    • The client connects by matching the server's machine and port, assigning its local port.

    • Connection process success results in a new socket for communication.

TCP Client/Server Interaction

  • Client Steps:

    1. Create a TCP socket.

    2. Communicate with the server.

    3. Close the connection.

  • Server Steps:

    1. Create a TCP socket.

    2. Continuously:

    • Accept new connections.

    • Communicate.

    • Close connections.

TCP Sockets in Java: Client Side

  • The java.net.Socket class is foundational for client-side TCP operations.

    • Other classes, such as URL and URLConnection, invoke methods from this class.

Basic Socket Constructors

  • Each constructor specifies the host and port for connection.

  • Host can be specified as InetAddress or String:

    • public Socket(String host, int port)

    • public Socket(InetAddress host, int port)

  • Port numbers range from 1 to 65535.

  • Constructors establish active network connections, throwing IOException or UnknownHostException on failure.

Using Socket() to Scan Ports

import java.net.*;
import java.io.*;
public class LowPortScanner {
    public static void main(String[] args) {
        String host = args.length > 0 ? args[0] : "localhost";
        for (int i = 1; i < 1024; i++) {
            try {
                Socket s = new Socket(host, i);
                System.out.println("There is a server on port " + i + " of " + host);
                s.close();
            } catch (UnknownHostException ex) {
                System.err.println(ex);
                break;
            } catch (IOException ex) {
                // no server on this port
            }
        }
    }
}

Creating Unconnected Sockets

  • Constructors to create unconnected sockets allow more control (e.g., different proxies/encryption):

    • public Socket() - no immediate connection.

    • Can connect later using the connect() method with a SocketAddress.

The SocketAddress Class

  • Represents Socket Address for storing connection info (IP address and port).

  • Provides two methods:

    • getRemoteSocketAddress() - returns the address of the connected system.

    • getLocalSocketAddress() - returns the address of the local bound system.

The InetSocketAddress Class

  • Subclass of SocketAddress created with:

    • public InetSocketAddress(InetAddress address, int port)

    • public InetSocketAddress(String host, int port)

    • public InetSocketAddress(int port)

Polymorphism Revisited

  • Polymorphism allows connecting to sockets via different methods while treating them uniformly.

  • Example: Using Socket and SocketAddress interchangeably.

TCP Client/Server Interaction Details

  • Detailed steps for Client and Server interactions were discussed, highlighting continuous acceptance of connections, communication, and closure of connections.

TCPEcho Client Implementation

  • Client uses Socket to connect, sending and receiving data via I/O streams:

    1. Create a socket connection to the server.

    2. Use PrintWriter for output and BufferedReader for input.

  • Example implementation noted in the textbook.

The Echo Protocol

  • A service in the Internet Protocol Suite designed for testing by sending back identical data received. Uses TCP/UDP on port 7.

Socket Class: I/O Operations

  • Methods for communicating via InputStream and OutputStream to handle remote system data exchange.

  • getInputStream(), getOutputStream() return the associated streams.

The InputStream Class

  • Basic class for reading raw byte data. Methods include:

    • public abstract int read()

    • public int read(byte[] input)

  • Proper implementations for efficient multi-byte reading are discussed in example code blocks.

The OutputStream Class

  • Class for writing data. Key functions:

    • public abstract void write(int b)

    • public void write(byte[] data)

    • Use flush() to ensure buffer data is sent correctly.

The TCPEchoServer Class

  • Implements the echo server functionality. Steps involve:

    1. Construct ServerSocket for the desired port.

    2. Continuously accept connections and service them until closed.

  • Example socket implementation provided in the textbook.

The NetworkInterface Class

  • Represents a local IP address and methods to enumerate local addresses are discussed, demonstrating how to create Socket and ServerSocket from those addresses.

Error Handling in Networking

  • Various exceptions such as SocketException, UnknownHostException, and IOException are discussed. Proper error handling mechanisms are illustrated throughout the examples.