PHP Socket Communication Demo and socket operation class, phpsocket_php tutorial

Source: Internet
Author: User
Tags php server set socket socket connect socket error

PHP Socket Communication Demo and socket operation class, Phpsocket


  

Ready to do the Java course design, an address book. Adopt C/S architecture. The client uses Java FX and Java, server side with PHP, socket communication.

Here's a talk about the socket for PHP:

  Before you speak , you have to talk about TCP/IP,UDP first. With the increasing use of the Internet, it is believed that many people have heard about these protocols, so what are they?

  1, what is TCP/IP, UDP?

TCP/IP (transmission Control protocol/internet Protocol) is the transmission protocol /Inter-network protocol, is an industry-standard protocol set that is designed for wide area networks (WANs). The TCP/IP protocol family includes transport layer, network layer, and link layer.
UDP (user Data Protocol, Subscriber Datagram Protocol) is the protocol that corresponds to TCP. It is a part of the TCP/IP protocol family.

Here's a visual representation of their relationship:

There's no socket here, so where is the socket? What's the use? Don't worry, let's introduce the socket to their relationship. Same.

      
Now understand their relationship. What exactly is the socket? What's the use?

2. What is socket? What's the use?

    A socket is an intermediate software abstraction layer that the application layer communicates with the TCP/IP protocol family, which is a set of interfaces. In design mode, the socket is actually a façade mode, it is the complex TCP/IP protocol family hidden behind the socket interface, for the user, a set of simple interface is all, let the socket to organize data to meet the specified protocol.

Since the socket is a well-encapsulated set of interfaces, how do we use it to communicate? What is a specific process? We can detail the process of our telephone call. First of all, our phone must be in the listening state, right. If not, it would certainly not have received a call from someone else. When people call, the first is to dial first, the number is the target, but also the only. After dialing the phone will start to connect, after the connection can begin to talk, after the chat is over to hang up the phone so that others can get through this number. Socket is the same, the server must first establish a socket to listen to their own computer a port, when a client creates a socket to initiate a connection request to accept, so that the message can begin to transfer, after the transfer of the socket closed. Of course, the server side can also initiate a connection request to the client and then start the communication. This is different from Ajax, which can be communicated in two directions. Look at the following picture:

        

Start with the server side. The server-side initializes the socket, then binds to the port (BIND), listens to the port (listen), calls the Accept block, waits for the client to connect. At this point if a client initializes a socket and then connects to the server (connect), the client-server connection is established if the connection is successful. The client sends a data request, the server receives the request and processes the request, then sends the response data to the client, the client reads the data, closes the connection, and ends the interaction at once.

3, the socket related functions:

Socket_accept () accepts a socket connection
Socket_bind () binds the socket to an IP address and port
Socket_clear_error () Clears the socket error or the last error code
Socket_close () Close a socket resource
Socket_connect () Start a socket connection
Socket_create_listen () Open a socket listener on the specified port
Socket_create_pair () produces a pair of undifferentiated sockets into an array
Socket_create () produces a socket equivalent to a data structure that produces a socket
Socket_get_option () Get socket options
Socket_getpeername () Gets the IP address of a remote similar host
Socket_getsockname () Gets the IP address of the local socket
Socket_iovec_add () Add a new vector to a scatter/aggregate array
Socket_iovec_alloc () This function creates a IOVEC data structure that can send the received read and write
Socket_iovec_delete () Delete an assigned Iovec
Socket_iovec_fetch () returns the data for the specified Iovec resource
Socket_iovec_free () releasing a Iovec resource
Socket_iovec_set () Sets the new data value of the Iovec
Socket_last_error () Gets the last error code for the current socket
Socket_listen () listens for all connections by the specified socket
Socket_read () reads the specified length of data
SOCKET_READV () reads data from a scatter/aggregate array
SOCKET_RECV () end data from socket to cache
Socket_recvfrom () accepts data from the specified socket, if not specified, the default current socket
Socket_recvmsg () receive messages from Iovec
Socket_select () multi-channel selection
Socket_send () This function sends the data to the connected socket
SOCKET_SENDMSG () Send message to socket
Socket_sendto () sends a message to the socket at the specified address
Socket_set_block () set as block mode in socket
Socket_set_nonblock () set to non-block mode in socket
Socket_set_option () Set socket options
Socket_shutdown () This function allows you to close a read, write, or specified socket
Socket_strerror () returns a detailed error for the specified error number
Socket_write () write data to the socket cache
Socket_writev () write data to a scatter/aggregate array

4. Socket Communication Demo:

Server-side:
Php//Ensure that the client is not timed out when connectingSet_time_limit(0);$ip= ' 127.0.0.1 ';$port= 1935;/*+-------------------------------* @socket communication throughout the process +-------------------------------* @socket_create * @socket _bind * @socket_listen * @socket_accept * @socket_read * @socket_write * @socket_close +------------------- ------------- */if(($sock= Socket_create (af_inet,sock_stream,sol_tcp)) < 0) { EchoThe reason for the socket_create () failure is: ". Socket_strerror ($sock)." \ n ";}if(($ret= Socket_bind ($sock,$ip,$port)) < 0) { EchoThe reason for the Socket_bind () failure is: ". Socket_strerror ($ret)." \ n ";}if(($ret= Socket_listen ($sock, 4)) < 0) { EchoThe reason for the Socket_listen () failure is: ". Socket_strerror ($ret)." \ n ";}$count= 0; Do { if(($msgsock= Socket_accept ($sock)) < 0) { Echo"Socket_accept () Failed:reason:". Socket_strerror ($msgsock) . "\ n"; Break; } Else { //Send to client $msg= "Test succeeded!" \ n "; Socket_write ($msgsock,$msg,strlen($msg)); Echo"The test was successful. \ n"; $buf= Socket_read ($msgsock, 8192); $talkback= "Information Received:$buf\ n "; Echo $talkback; if(++$count>= 5){ Break; }; } socket_close ($msgsock);} while(true); Socket_close ($sock);?>
Client
Phperror_reporting(E_all);Set_time_limit(0);$ip= "127.0.0.1";$port= 1935;/*+-------------------------------* @socket connect the whole process +-------------------------------* @socket_create * @socket _connect * @socket_write * @socket_read * @socket_close +--------------------------------*/$socket= Socket_create (Af_inet, Sock_stream,sol_tcp);if($socket< 0) { Echo"Socket_create () Failed:reason:". Socket_strerror ($socket) . "\ n";}Else { Echo"Ok.\n";}Echo"Trying to connect"$ipPort$port' ... \ n ';$result= Socket_connect ($socket,$ip,$port);if($result< 0) { Echo"Socket_connect () Failed.\nreason: ($result) " . Socket_strerror ($result) . "\ n";}Else { Echo"Connect ok\n";}$in= "ho\r\n";$in. = "First blood\r\n";$out= '';if(!socket_write ($socket,$in,strlen($in))) { Echo"Socket_write () Failed:reason:". Socket_strerror ($socket) . "\ n";}Else { Echo"Send message to server successfully!" \ n "; Echo"The content sent is:$in
";} while($out= Socket_read ($socket, 8192)) { Echo"The receiving server backhaul information is successful!" \ n "; Echo"The accepted content is:",$out;}Echo"Close socket...\n"; Socket_close ($socket);Echo"Close ok\n";?>

  Note: 1) The server side is running in CLI mode, which is the command line pattern. Do not use CGI (browser access); Locate the directory where the Php.exe is located, and then run the following code, PHP server files;

    

2) Run Netstat-ano to view port occupancy after running under another DOS window.

    

5. Package the socket into a class:

ServerSocket.class.php
Client socket Operation class
 Phperror_reporting(E_all); Set_time_limit(0); classServerSocket {Private $server _host;//Server IP     Private $server _port;//Server Port     Private $client _host;//Client IP     Private $client _port;//Client Port     Private $create _socket=NULL; Private $accept _socket=NULL; Private $get _data=""; Private $send _data=""; //enough to create a function      Public function__construct ($host,$port){         if(!extension_loaded("Socket")){             Exit("Please open the socket extension first!") "); }         if(Empty($host))              Exit("Please enter the target host ip! "); if(Empty($port))             Exit("Please enter a valid port number!") "); $this->server_host=$host; $this->server_port=$port; $this-Createsocket (); }          //Create a socket and use it to bind the listening port     Private functionCreatesocket () {if($this->create_socket = Socket_create (Af_inet, sock_stream, sol_tcp) = =false){                 Echo"Socket_create () failed. Reason: ". Socket_strerror (Socket_last_error ())." \ n "; }           if(Socket_bind ($this->create_socket,$this->server_host,$this->server_port) = =false){               Echo"Socket_bind () failed. Reason: ". Socket_strerror (Socket_last_error ($this->create_socket)). " \ n "; }           if(Socket_listen ($this->create_socket,5) = =false){               Echo"Socket_listen () failed. Reason: ". Socket_strerror (Socket_last_error ($this->create_socket)). " \ n "; }             }          //initiating a connection to the target host      Public functionconnectclient () {if(Socket_getpeername ($this->create_socket,$this->client_host,$this->client_port) = =NULL){             Echo"Socket_getpeername () failed. Reason: ". Socket_strerror (Socket_last_error ($this->create_socket)). " \ n "; }         if(Socket_connect ($this->create_socket,$this->client_host,$this->client_port) = =false){             Echo"Socket_connect () failed. Reason: ". Socket_strerror (Socket_last_error ($this->create_socket)). " \ n "; }     }     //accepts a connection gets to a socket resource, wants the client to read and transmit information      Public functionWR () { Do{//loops to prevent blocking delays             if($this->accept_socket=socket_accept ($this->create_socket) = =NULL){                 Echo"Socket_accept () failed. Reason: ". Socket_strerror (Socket_last_error ($this->create_socket)). " \ n ";  Break; }                          $this->get_data = Socket_read ($this->accept_socket, 8192); $this->send_data=$this->operatedata ($this-get_data); if(Socket_write ($this->accept_socket,$this->send_data,strlen($this->send_data)) = =false) {                 Echo"Socket_write () failed reason:". Socket_strerror (Socket_last_error ($this->accept_socket)). " \ n "; } socket_close ($this-accept_socket); } while(true); }          //Data Processing     Private functionOperatedata () {return ; }          //turn off the monitor socket     Private functionclosesocket () {Socket_close ($this-createsocket); }          // Destructors      Public function__destruct () {$this-closesocket (); }   }        
//clientsocket.class.php//Client Socke operation classclassSocket {Private $host;//the host connecting to the socket    Private $port;//port number of the socket    Private $error=Array(); Private $socket=NULL;//connection identification of the socket    Private $queryStr="";//the data sent     Public function__construct ($host,$port) {        if(!extension_loaded("Sockets")){            Exit("Please open the socket extension"); }        if(Empty($host))Exit("Please Enter Destination address"); if(Empty($port))Exit("Please enter a valid port number"); $this->host=$host; $this->port=$port; $this->createsocket ();//Create a connection    }    //Create socket    Private functionCreatesocket () {!$this->socket&&$this->socket=socket_create (Af_inet, Sock_stream, sol_tcp);//Create socket        $r= @socket_connect ($this->socket,$this->host,$this-port); if($r){            return $r; }Else{            $this->error[]=socket_last_error ($this-socket); return false; }    }    //writes data to the socket server and reads     Public functionwr$contents){        $this->querystr= ""; $this->querystr=$contents; !$this->socket&&$this-Createsocket (); $contents=$this->flitersenddata ($contents); $result=socket_write ($this->socket,$contents,strlen($contents)); if(!intval($result)){            $this->error[]=socket_last_error ($this-socket); return false; }        $response=socket_read ($this->socket,12048); if(false===$response){            $this->error[]=socket_last_error ($this-socket); return false; }        return $response; }    //filtering the data that is sent    Private functionFlitersenddata ($contents){        //processing of the data being written        return $contents; }    //all error Messages     Public functionGetError () {return $this-error; }    //Last error message     Public functionGetLastError () {return $this->error (Count($this-error)); }        //get the last message sent     Public functiongetlastmsg () {return $this-Querystr; }     Public functionGetHost () {return $this-host; }     Public functionGetport () {return $this-Port; }    //Close the socket connection    Private functionClose () {$this->socket&&socket_close ($this->socket);//Close Connection        $this->socket=NULL;//Connection Resource Initialization    }     Public function__destruct () {$this-Close (); }}

http://www.bkjia.com/PHPjc/1125072.html www.bkjia.com true http://www.bkjia.com/PHPjc/1125072.html techarticle PHP Socket Communication Demo and socket operation class, phpsocket ready to do Java course design, an address book. Adopt C/S architecture. Client with Java FX and Java, server side with PHP, using s ...

  • Related Article

    Contact Us

    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.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.