This article mainly introduces the usage of fsockopen in php. The example analyzes the specific procedures of fsockopen, such as creating, writing, and closing. if you need it, refer to the example in this article to describe the usage of fsockopen in php. Share it with you for your reference.
The specific implementation method is as follows:
The code is as follows:
$ Fp = fsockopen ("127.0.0.1", 80); // open the data stream
If (! $ Fp) // if an error occurs
{
Echo "unable to openn"; // Output Content
}
Else // if it is enabled successfully
{
Fwrite ($ fp, "get/http/1.0 rnrn"); // write content to the data stream
Stream_set_timeout ($ fp, 2); // Set the timeout
$ Res = fread ($ fp, 2000); // read content
$ Info = stream_get_meta_data ($ fp); // Get the data stream header
Fclose ($ fp); // Close the data stream
If ($ info ['timed _ out']) // if timeout
{
Echo 'connection timed out! '; // Output Content
}
Else
{
Echo $ res; // output read content
}
}
// Instance 2
// Create a server
$ Socket = stream_socket_server ("tcp: // 0.0.0.0.0: 8000", $ errno, $ errstr );
// If creation fails
If (! $ Socket)
{
Echo "$ errstr ($ errno)
N ";
}
// If creation is successful
Else
{
// Accept the connection
While ($ conn = stream_socket_accept ($ socket ))
{
// Write data
Fwrite ($ conn, 'The local time is '. date ('N'/j/y g: I a'). "n ");
// Close the connection
Fclose ($ conn );
}
// Close the socket
Fclose ($ socket );
}
//
$ File = "test.txt"; // definition file
$ Fp = fopen ($ file, "w"); // open the data stream
If ($ fp) // if enabled successfully
{
Stream_set_write_buffer ($ fp, 0); // you can specify a buffer.
Fwrite ($ fp, $ output); // write content
Fclose ($ fp); // Close the data stream
}
I hope this article will help you with php programming.