Application instance analysis based on phpsocket (fsockopen)
Source: Internet
Author: User
This article provides a detailed analysis of phpsocket (fsockopen) application instances. if you need to use the fsockopen function, you must first enable allow_url_open = on in php. ini;
Fsockopen is the encapsulation of socket client code. this function encapsulates socket_create and socket_connect.
Server code: server. php The code is as follows:
Error_reporting (E_ALL );
Set_time_limit (0 );
$ Address = '1970. 0.0.1 ';
$ Port = 10008;
// Create a port
If ($ sock = socket_create (AF_INET, SOCK_STREAM, SOL_TCP) = false ){
Echo "socket_create () failed: reason:". socket_strerror (socket_last_error (). "\ n ";
}
// Bind
If (socket_bind ($ sock, $ address, $ port) === false ){
Echo "socket_bind () failed: reason:". socket_strerror (socket_last_error ($ sock). "\ n ";
}
// Listen
If (socket_listen ($ sock, 5) === false ){
Echo "socket_bind () failed: reason:". socket_strerror (socket_last_error ($ sock). "\ n ";
}
While (true ){
// Get a link
If ($ msgsock = socket_accept ($ sock) === false ){
Echo "socket_accepty () failed: reason:". socket_strerror (socket_last_error ($ sock). "\ n ";
Break;
}
// Send welcome to the client
$ Msg = "1. server send: welcome
";
Socket_write ($ msgsock, $ msg, strlen ($ msg); // return information to the client
Echo 'read client message \ n ';
$ Buf = socket_read ($ msgsock, 8192); // obtain the information sent from the client.
$ Talkback = "2. received message: $ buf \ n ";
Echo $ talkback;
If (false === socket_write ($ msgsock, $ talkback, strlen ($ talkback) {// return information to the client
Echo "socket_write () failed reason:". socket_strerror (socket_last_error ($ sock). "\ n ";
} Else {
Echo 'send success ';
}
Socket_close ($ msgsock );
}
Socket_close ($ sock );
Client code: fsocket. php
The code is as follows:
$ Fp = fsockopen ("127.0.0.1", 10008, & $ errno, & $ errstr, 10 );
If (! $ Fp ){
Echo $ errstr. "(". $ errno .")
N ";
} Else {
$ In = "HEAD/http/1.1 \ r \ n ";
$ In. = "HOST: localhost \ r \ n ";
$ In. = "Connection: close \ r \ n ";
Fputs ($ fp, $ in );
While (! Feof ($ fp )){
Echo fgets ($ fp, 128 );
}
Fclose ($ fp );
}
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.