Java – What’s the difference between SocketAddress and ServerSocket in Java

javanetworking

Learning how to develop a small embedded HTTP server for a class assignment, and the examples given on how to use com.sun.net.httpserver.HttpServer use an InetSocketAddress which extends SocketAddress as the link between client and server. However, all of my previous network programming assignments used Socket and ServerSocket to create raw connections between a server and client to send custom protocols back and forth.

Clearly these two classes are different as they don't share any common ancestor other than java.lang.Object. What is inherently special about each that makes them fundamentally different?

Best Answer

It is all in the name... A typical network socket is a connection between two ports on two machines.

The ServerSocket is the one that waits for clients to connect to it.... it 'binds' to a port, and it 'Listens' for connections, and when they happen, it 'accepts' the connection. The result of the accepted connection is a Java Socket. The client that connected (if it is also Java), also has a Java Socket. You now have two sockets connected to each other.

The Socket is described above.

Now, the address is the details about how to find/identify the remote side of the Socket connection.

A SocketAddress is the abstract class for something that can tell Java where to connect to when contacting a server, and it allows the Sockets to identify remote servers/clients once the connection is made.

An InetSocketAddress is a special SocketAddress designed to represent the standard TCP Protocol address, so it thus has methods to set/query the host name, IP address, and Socket of the remote side of the connection (or, in fact the local side too).

So, the (Inet)Socket address is used to establish Socket connections...

Summary:

  • ServerSocket is a listener that waits for socket connections to be established.
  • Socket is the communication channel between two systems (one the server, the other the client).
  • SocketAddress is an abstract class that identifies an address
  • InetSocketAddress is a class that is specific for the TCP protocol consisting of IP Addresses/host-names, and port numbers. This is used to establish internet/TCPIP sockets.