Socket programming, commonly used in C or C + +. Especially in Web application development, Perl is commonly used to implement sockets. In addition, using PHP for socket programming is also a choice. PHP is capable of doing it. Of course. PHP is a high-quality Web application development language, many of his features can handle a large number of tasks, network programming is no exception.
1. Understanding sockets
Mail, FTP, Telnet, name, and finger these services are provided on a dedicated, exposed port that the client program can access by connecting to these ports. This is similar to real life-when it comes to dry cleaning, find a dry cleaner, go to the bank, and so on when you need to pick up the money. In addition to the port that is dedicated to a particular server, the computer has other ports for programmers to create their own servers. The port is typically numbered, and the client can connect to the port by specifying the server's port number. Each server or port requires a specific protocol, and in order for the customer's request to be understood and responded to, the customer must form a customer request in such a way that the server is unique. The socket is one end of a two-way communication connection between two programs running on the network. The general meaning of the word socket is natural or artificial socket, such as the power socket of household appliances. The client can write a request to the socket, the server processes the request, and then returns the result to the customer via the socket. A socket is a low-level connection. The client and the server communicate by writing a byte stream to the socket. They must have a common protocol, that is, the language used to transmit information to each other through the socket must be a good agreement.
2. Socket to establish the process of connection
The establishment process is as follows: (connection-oriented)
server-side procedures |
|
Client Side Process |
Socket () |
|
Socket () |
Bind () |
|
Bind () |
Listen () |
|
↓ |
Accept () |
← |
Connect () |
Recv ()/Send () |
←→ |
Send ()/recv () |
3. PHP Basic Socket Call: 3.1.) Basic socket Call Create socket--socket (); Bind the Machine port--bind (); Establish connection--connect (), accept (); Listening port--listen (); Data transmission--send (), recv (); Input/Output multiplexing--select (); Close Socket--closesocket () 3.2.) PHP provides socket calls: Accept connection--accept Connect () Bind Port-bind () Close Socket-close () Initialize Connection-connect () Listening Port-listen () Read Socket-read () Create Socket-socket () Write Socket-write () 4. Basic Application
4.1.) A simple TCP server 1 #!/usr/local/bin/php-q 2 3 <?php 4/* 5 * We don ' t want any time-limit to how the long can hang 6 * Around, waiting for connections: (using Set_time_limit Set Program execution time is infinite to wait for connection) 7 */ 8 Set_time_limit (0); 9 Create a new socket: (Creating a socket) * * One if (($sock = socket (af_inet, sock_stream, 0)) < 0) 12 { Print strerror ($sock). "N"; Exit (1); 15} 16 /* Bind the socket to A and port: (Bind created socket to IP and port) * * if ($ret = bind ($sock, "10.31.172.77", 10000)) < 0) 19 { Print strerror ($ret). "N"; Exit (1); 22} 23 24/* * Listen for incoming connections on $sock. * the ' 5 ' means that we allow 5 queued connections. (Listening port) 27 */ if ($ret = Listen ($sock, 5)) < 0) 29 { Print strerror ($ret). "N"; 31} 32 Accept/* Incoming connections: (Accept connection) * * if ($msgsock = Accept_connect ($sock)) < 0) 35 { Print strerror ($msgsock). "N"; Panax Notoginseng exit (1); 38} 39 /* Send the Welcome-message: (Show welcome information) * * $message = "Welcome to my Tcp-server!n"; if ($ret = Write ($msgsock, $message, strlen ($message)) < 0) 43 { The print strerror ($msgsock). "N"; The exit (1); 46} 47 Read/receive/* Some data from the client: (read client information) * * $buf = '; if ($ret = Read ($msgsock, $BUF, 128)) < 0) 51 { Print strerror ($ret). "N"; Exit (1); 54} 55 * * echo the received data back to the client: (Echo message to clients) ($ret = Write ($msgsock, "said: $bufn", strlen ("You said: $bufn")) < 0) 58 { Print strerror ($ret). "N"; Exit (1); 61} 62 /* Close the Communication-socket: (Off socket) * * Close ($msgsock); 65 * * Close the global socket: * * Close ($sock); ?> 4.2.) Running of a TCP server The top of this TCP server's run requires PHP to be compiled into a CGI interpretation, and add--enable-sockets when compiling. If you have compiled a CGI interpretation to run, but the items listed with the command php-m have no sockets, you will need to recompile PHP. When these requirements are met, you can run the server. To start the server: ./filename.php You can then log on using Telnet. Telnet 10.31.172.77 10000 Your terminal will show: Trying 10.31.172.77 ... Connected to 10.31.172.77. Escape character is ' ^] '. Welcome to my TCP server! Then enter something, and return: Hello You Said:hello Connection Closed by foreign host You can also modify the program to make it look like the example on Phpmanual, which closes the connection only when the client enters "quit". 5. Other applications
5.1.) Chat Room Application
5.1.1.> Common chat Room implementation
A common way to implement a chat room is to use a frames page and then refresh it using HTML for one of the frames used to display the conversation, for example: <meta http-equiv= "Refresh" content= "3;http://www.jite.net" > Using this approach can cause the browser to make a continuous request to the server, and when there is a large number of requests, the server will run inefficiently. This kind of chat room is obviously flawed in design. But if you use the socket to implement the chat room, the situation is different. 5.1.2.> use socket to realize chat room The chat room we want to discuss is very simple, just a principle implementation. It is a CLIENT/SERVER structure program that starts the server first, and then the user connects using the client. The advantage of the client/server structure is that it is fast, and the disadvantage is that when the server updates, the client also needs to be updated. Initialize the server to allow the server to enter the listening state: (The following is the principle of implementation and does not involve specific procedures) $socket = socket (af_inet,sock_stream, 0); First set up a socket, the family is af_inet, the type is sock_stream. Af_inet = ARPA Internet protocols that uses the TCP/IP protocol family The Sock_stream type provides a sequential, reliable, Full-duplex connection based on a byte stream. Because there is only one protocol in the Protocol family, the third parameter is 0 Bind ($sock, $address, $port) The socket is then bound to an address. Listen (SOCKFD, max_client) After the address binding, the server enters the listening state. Max_client is the total number of CLIENT connections that can be established at the same time. After the server enters the listen state, it waits for the client to establish a connection. The client side will first need to initialize the connection to establish the connection: $socket = socket (af_inet,sock_stream,0)) Similarly, the client first creates a socket with the same parameters as the server. Connect ($socket, $address, $service _port) Client uses connect to establish a connection. When the client's request to establish a new connection is sent to the server side, the server uses accept to accept the connection: Accept_connect ($sock) Accept returns a new file descriptor. After the server has entered the Listen state, the program needs to manipulate these users and exchange information between them because there may be more than one user requesting a connection. This is called I/O multiplexing technology in implementation. I/O multiplexing technology is not the content of this article to be described, if interested please refer to the relevant books. 5.2.) A web-based newsgroup browser
You can use Fsockopen to open a TCP socket connection in PHP int Fsockopen (string hostname, int port [, int errno [, String errstr [, double timeout]]] Refer to the PHP manual for the use of this function. To access the newsgroup service, you need to use a protocol called NNTP, that is, network news Transfer Protocol. This protocol has a dedicated RFC description, which is located in http://www.w3.org/Protocols/rfc977/rfc977.html. This document details how to chat with an NNTP server and how to use commands to accomplish tasks. 5.2.1. > Connect a server <?php $cfgServer = "News.php.net"; $cfgPort = 119; $cfgTimeOut = 10; Open a socket if (! $cfgTimeOut) Without timeout $usenet _handle = Fsockopen ($cfgServer, $cfgPort); Else With timeout $usenet _handle = Fsockopen ($cfgServer, $cfgPort, & $errno, & $errstr, $cfgTimeOut); if (! $usenet _handle) { echo "Connexion Failedn"; Exit (); } else { echo "Connectedn"; $tmp = fgets ($usenet _handle, 1024); } ?> 5.2.2. > Dialogue with the Server In the front, we are already connected to the server, what if we want to select 10 Recent news from a newsgroup? RFC977 that select a newsgroup to use the Group command: GROUP GGG <?php $cfgUser = "xxxxxx"; $CFGPASSWD = "yyyyyy"; $cfgNewsGroup = "alt.php"; Identification required on private server if ($cfgUser) { Fputs ($usenet _handle, "AUTHINFO USER". $cfgUser. " n "); $tmp = fgets ($usenet _handle, 1024); Fputs ($usenet _handle, "AUTHINFO Pass". $cfgPasswd. " n "); $tmp = fgets ($usenet _handle, 1024); Check error if ($tmp!= "281 okrn") { echo "502 Aut Hentication Errorn; exit (); } } //select newsgroup Fputs ($usenet _handle, "GROUP". $cfgNewsGroup. " n "); $tmp = fgets ($usenet _handle, 1024); if ($tmp = =" Authentication required for Commandrn ") { &NBSP Echo "$TMPN"; Exit (); } $info = Split ("", $tmp) $first = $info [2] $last = $info [3]; Print "A: $firstn"; Print "Last: $lastn"; > ; 5.2.3. > Read the news The command to read the news is article, please refer to RFC977 for specific use, no routines are provided here. &NBSP 6. PostScript I thought I'd written one last time, so I can avoid it. A few days before the deadline, Yu Rongxian to manuscripts. Process draft hasty, inevitable mistakes, please forgive me, and pointed out. &NBSP 7. References: Liao Bin, PHP daemon programming, , "RFC977", Daniel solin,introduction to Socket programming with PHP; |