Sobes.tech
Junior

What is a socket?

sobes.tech AI

Answer from AI

A socket is an abstraction of an endpoint for bidirectional network communication between two programs over a network.

In the context of network programming, a socket is a software object that:

  • is identified by a pair of IP address + port.
  • serves as an interface for sending and receiving data.
  • provides a way for processes to exchange information, regardless of whether they are on the same or different machines.

There are two main types of sockets depending on the transport layer protocol used:

  1. TCP sockets (stream):
    • use the TCP protocol.
    • provide reliable, connection-oriented data stream transmission.
    • guarantee data delivery, order preservation, and no duplicates.
    • are used for protocols requiring reliable transmission (HTTP, FTP, SSH).
  2. UDP sockets (datagram):
    • use the UDP protocol.
    • represent unreliable, connectionless data transmission in the form of datagrams.
    • do not guarantee delivery, order, or absence of duplicates.
    • are used for protocols where speed is more important than reliability (DNS, streaming video/audio).

In Java, socket programming is implemented using classes from the java.net package:

  • Socket for client TCP sockets.
  • ServerSocket for server TCP sockets.
  • DatagramSocket for UDP sockets.
  • DatagramPacket for UDP datagrams.

Example of a simple TCP client:

import java.net.Socket;
import java.io.OutputStream;

// TCP client class
public class SimpleTcpClient {

    // Method to create and use a socket
    public static void main(String[] args) {
        try {
            // Create a client socket, connect to server at localhost:12345
            Socket socket = new Socket("localhost", 12345);
            System.out.println("Connected to server.");

            // Get output stream to send data
            OutputStream outputStream = socket.getOutputStream();
            String message = "Hello from client!";
            outputStream.write(message.getBytes()); // Send data

            // Close the socket
            socket.close();
            System.out.println("Socket closed.");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}