How do I work with sockets

Working with sockets in programming allows for communication between devices and applications over a network. Sockets are endpoints for sending and receiving data across the network. In this guide, we'll cover the basics of creating a simple socket connection using PHP.

Keywords: sockets, networking, PHP, communication, programming
Description: This tutorial provides an introduction to sockets in PHP, including examples of creating socket connections and communicating between servers and clients.

<?php
// Creating a TCP/IP socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    echo "Failed to create socket: " . socket_strerror(socket_last_error()) . "<br>";
}

// Binding the socket to an address and port
$bind = socket_bind($socket, '127.0.0.1', 8080);
if ($bind === false) {
    echo "Failed to bind socket: " . socket_strerror(socket_last_error($socket)) . "<br>";
}

// Listening for incoming connections
socket_listen($socket);

// Accepting a connection
$clientSocket = socket_accept($socket);
if ($clientSocket === false) {
    echo "Failed to accept connection: " . socket_strerror(socket_last_error($socket)) . "<br>";
}

// Reading data from the client
$input = socket_read($clientSocket, 1024);
echo "Received data: " . $input . "<br>";

// Sending a response back to the client
$response = "Hello Client!";
socket_write($clientSocket, $response, strlen($response));

// Closing the sockets
socket_close($clientSocket);
socket_close($socket);
?>
    

Keywords: sockets networking PHP communication programming