ServerSocket & Socket Introduction Tutorial

The ServerSocket and Socket class work hand-in-hand for providing communication links over TCP/IP networks. In order to follow along with this tutorial you will need just a basic understanding of how networks work. The best example of a TCP/IP network is the Internet. Let's talk about this website - JavacJava.com - for a moment. I have a virtual server from Amazon Web Services (AWS) running Windows Server 2012 R2. That server is assigned to a public static IP address of 52.24.233.53, which AWS provides to me. It is running Internet Information Services (IIS) which listens for incoming connections on port 80. Generally speaking, there are a maximum of 65,535 ports available to listen for incoming connections - although many of those are reserved by the OS for various things. On the other end of connection is your computer - your computer is connected to the Internet via a service provider that provided you with a gateway (hardware) that gets assigned a public IP address when it connects to their network. When you connect your computer to the gateway via a network cable or wirelessly, your computer gets a local IP address. When you open up your browser and browse to www.JavacJava.com, a connection request is made to my server at 52.24.233.53 over port 80.

ServerSocket and Socket

Both classes implement AutoClosable so we can use the try-with-resources type exception handling. I am going to create server program that listens for incoming requests over TCP port 4141. To keep things simple the server will simply respond to connection requests with a Hello message. Let's get started...



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md Sockets
C:\Java>cd Sockets
C:\Java\Sockets>Notepad Server.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


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

public class Server {
    public static void main(String[] args) {
        System.out.println("Listening on port 4141, CRTL-C to stop");
        try(ServerSocket serverSocket = new ServerSocket(4141)) {
            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("Got a connection!");
                try (PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {  // true is auto flush
                    out.println("Hello from the server socket.");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();	
        }
    }
}

Now switch back to the command prompt (CMD) and type in javac Sockets.java and press Enter.
Now type in java Sockets and press Enter.


C:\Java\Sockets>javac Server.java
C:\Java\Sockets>java Server

Type in the following commands into a new dos prompt on the Java\Sockets folder.


C:\Java\Sockets>Notepad Client.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


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

class Client {
    public static void main(String[] args) {
        try (Socket s = new Socket(InetAddress.getByName("10.0.0.183"), 4141)) { // change the IP address to your server's ip address
            BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
            System.out.println(input.readLine());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Now switch back to the command prompt (CMD) and type in javac Sockets.java and press Enter.
Now type in java Sockets and press Enter.


C:\Java\Sockets>javac Client.java
C:\Java\Sockets>java Client
See Video

Final thoughts

None


Tutorials