How To Enable Sockets

Table of contents:

How To Enable Sockets
How To Enable Sockets

Video: How To Enable Sockets

Video: How To Enable Sockets
Video: WebSockets in 100 Seconds u0026 Beyond with Socket.io 2024, December
Anonim

Sockets are used in the programming language (PL) PHP to exchange information with the server. Some applications require the use of sockets to transfer data and write service parameters. To enable the mode of connecting to the server, use the fsockopen () function, where the necessary connection parameters are set.

How to enable sockets
How to enable sockets

Instructions

Step 1

The fsockopen () function has the following syntax:

fsockopen (hostname, port);

In this case, hostname is the name of the server being accessed using sockets and opening a channel for data transmission. The port value is a number that corresponds to the port used to access the server.

Step 2

Use a text editor to write this code into your PHP file to start the socket data exchange operation. For example, to connect to a specific server.com on port 120, enter the following commands:

<? php

$ serv = “server.com”;

$ serv_port = 120;

$ open_con = fsockopen ($ serv, $ serv_port);

If (! $ Open_con) {

Exit (); } else {Echo “connection created”;

$ temporal = fgets ($ open_con, 1024); }

?>

Step 3

This code assigns the variables corresponding values with the server name ($ serv) and port number ($ serv_port). If there is no connection to the server, the script terminates its work via the exit () command. If the connection is successful, the program displays a notification about the creation of the connection and saves its parameters to the $ temporal variable.

Step 4

After using fsockopen (), you can use functions to manipulate files and retrieve data. So, in addition to the aforementioned fgets (), you can use fwrite () to write a file, fclose () to close, or feof () to check that the end of the file has been reached. This way you can record some data that is transmitted by the server you connected to. For example:

$ data_con = “GET / HTTP / 1.1 / r / n”;

$ data_con. = “Connection: Close / r / n / r / n”;

fwrite ($ open_con, $ data_con);

$ fclose ($ open_con);

Step 5

This request reads the GET headers sent by the server, and then writes the disconnection data from it with the corresponding parameters written in the $ data_con variable. The end of writing to a file is organized using the fclose () function.

Step 6

Opening a socket and writing connection data is complete. Save the file and upload it for testing on your hosting or local server.

Recommended: