Create a Socket (Client-Server) in Java

Tiempo de lectura: 3 minutos

Reading time: 4 minutes

Application communication is a fundamental part of software development as it allows data transfer and interaction between processes. In this regard, sockets are a key tool in implementing network communication in Java.

A socket is an endpoint of a connection between two processes that can be used to send and receive data. In general, there are two types of sockets: the client socket and the server socket. This article will explain how to create a client-server socket in Java using practical examples.

To begin, it is important to note that the server socket is responsible for listening for incoming connections and accepting them, while the client socket is the one that establishes a connection to the server. The following code shows how to implement a server socket in Java:

scss
try {
    // Create a server on port 8080
    ServerSocket serverSocket = new ServerSocket(8080);
    System.out.println("Server listening on port 8080...");

    // Wait for a client to connect
    Socket clientSocket = serverSocket.accept();
    System.out.println("Client connected from IP address " + clientSocket.getInetAddress().getHostAddress());

    // Close the server socket
    serverSocket.close();
} catch (IOException e) {
    e.printStackTrace();
}

In this example, a server socket is created on port 8080 using the ServerSocket class. Then, it waits for a client to connect using the accept() method of the ServerSocket class. When a client connects, its IP address is printed using the getInetAddress().getHostAddress() method of the Socket class.

Next, let’s see how to implement a client socket in Java:

scss
try {
    // Create a client socket and connect to the server at the specified IP address and port
    Socket clientSocket = new Socket("localhost", 8080);
    System.out.println("Connection established with server at IP address " + clientSocket.getInetAddress().getHostAddress());

    // Close the client socket
    clientSocket.close();
} catch (IOException e) {
    e.printStackTrace();
}

In this example, a client socket is created using the Socket class and connects to the server at the IP address localhost and port 8080. When the connection is established, the server’s IP address is printed using the getInetAddress().getHostAddress() method of the Socket class.

Once the client and server sockets have been created, communication can be established between them. Data input and output on the sockets are used to send and receive data.

The following example shows how to send data from the client socket to the server socket:

java
try {
    // Create a client socket and connect to the server at the specified IP address and port
    Socket clientSocket = new Socket("localhost", 8080);

    // Get the output stream from the client socket
    OutputStream outputStream = clientSocket.getOutputStream();

    // Send data to the server
    String message = "Hello, server!";
    outputStream.write(message.getBytes());

    // Close the client socket
    clientSocket.close();
} catch (IOException e) {
    e.printStackTrace();
}

In this example, a client socket is created and connects to the server at the IP address localhost and port 8080. Then, the output stream from the client socket is obtained using the getOutputStream() method of the Socket class. A message is created and sent to the server using the write() method of the OutputStream class.

On the other hand, the following example shows how to receive data on the server socket from the client socket:

scss
try {
    // Create a server on port 8080
    ServerSocket serverSocket = new ServerSocket(8080);

    // Wait for a client to connect
    Socket clientSocket = serverSocket.accept();

    // Get the input stream from the client socket
    InputStream inputStream = clientSocket.getInputStream();

    // Read the message sent by the client
    byte[] buffer = new byte[1024];
    int bytesRead = inputStream.read(buffer);
    String message = new String(buffer, 0, bytesRead);

    // Print the received message
    System.out.println("Message received from client: " + message);

    // Close the server socket
    serverSocket.close();
} catch (IOException e) {
    e.printStackTrace();
}

In this example, a server socket is created on port 8080 using the ServerSocket class. Then, it waits for a client to connect using the accept() method of the ServerSocket class. Once the client has connected, the input stream from the client socket is obtained using the getInputStream() method of the Socket class. The message sent by the client is read using the read() method of the InputStream class and printed to the console.

It is important to mention that in both examples, the close() method is used to close the sockets after performing the desired operation.

In conclusion, implementing a client-server socket in Java may seem complicated at first, but with some practice, smooth communication between two processes on a network can be achieved. It is important to understand the basics of sockets, such as socket types, data input and output, and socket management, in order to create a robust and secure network application.

Leave a Comment