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.
<?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);
?>
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?