# Java Socket Server Example

The tutorial explains to you how to create a server using a socket. This article has an example as well.

A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to.

a socket = protocol + hostname/IP (of the local machine) + port number

For instance, for an Oracle database it is common to have something like " server_hostname:1521 " as a socket.

In Java, the java.net package provides support for the two common network protocols: TCP & UDP.

When we use the TCP (transfer control protocol) a connection must first be established between the pair of sockets (client & server). While one of the sockets listens for a connection request (server), the other asks for a connection (client). Once two sockets have been connected, they can be used to transmit data in both (or either one of the) directions. Every TCP connection can be uniquely identified by its two endpoints. The TCP is a stream communication protocol and is used for implementing network services (such as rlogin, telnet and FTP).

The UDP (user datagram protocol) is a connectionless protocol. There is no guarantee that the datagrams you have sent will be received in the same order by the receiving socket (it is not a stream communication protocol). UDP is less complex than TCP and incurs fewer overheads. The UDP could be useful in some communications in distributed environments.

Here is a Java example of server using the sockets and the Transfer Control Protocol (TCP):

package server.socket.java.example;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
 
public class SimpleSocketServerExample {
 
    public static void main(String args[]) throws IOException {
         
        final int portNumber = 1887;
        System.out.println("Creating server socket on port " + portNumber);
         
        @SuppressWarnings("resource")
        ServerSocket serverSocket = new ServerSocket(portNumber);
         
        while (true) {
            Socket socket = serverSocket.accept();
            OutputStream os = socket.getOutputStream();
            PrintWriter pw = new PrintWriter(os, true);
            pw.println("Input 2 numbers with + sign between them:");
 
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String str = br.readLine();
   
            str = str.replace(" ", "");
            int plusSignPosition = str.indexOf("+");
             
            String str1 = str.substring(0, plusSignPosition);
            String str2 = str.substring(plusSignPosition+1);
             
            int number1 = Integer.parseInt(str1);
            int number2 = Integer.parseInt(str2);
            int sumVar = number1+number2;
                     
            pw.println("The sum of the 2 numbers is =  " + sumVar);
            pw.close();
            socket.close();
 
            System.out.println("The socket connection has been closed.");
        }
    }
}

First you have to export the project into a jar file and run it standalone or deploy it on a server. In my case I will run it on my computer :

When the Java client will change information with the server you will se on the server logs something like this:

A connection is created and closed for each client request. In my example, the server will respond to a request at a time.