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. Can PHP be qualified? 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 procedures
[Code]
Socket () socket ()
| |
Bind () bind ()
| |
Listen () |
| |
Accept () <------------------connect ()
| |
Recv ()/send () <----------> Send ()/recv ()
[/code]
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 ()
Socket calls provided by 3.2. PHP:
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
[Code]
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:
7 */
8 Set_time_limit (0);
9
Create a NEW 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: *
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.
num * the ' 5 ' means that we allow 5 queued connections.
27 */
if ($ret = Listen ($sock, 5)) < 0)
29 {
Print strerror ($ret). "\ n";
31}
32
Accept Incoming Connections: * *
if ($msgsock = Accept_connect ($sock)) < 0)
35 {
Print strerror ($msgsock). "\ n";
Panax Notoginseng exit (1);
38}
39
/* Send the welcome-message: * *
$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: * *
$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: * *
($ret = Write ($msgsock, "you said: $buf \ n", strlen ("you said: $buf \ n"))) < 0)
58 {
Print strerror ($ret). "\ n";
Exit (1);
61}
62
* * Close the communication-socket: * *
Close ($msgsock);
65
* * Close the global socket: * *
Close ($sock);
?>
[/code]
Line 8th: Use Set_time_limit to set the program execution time is infinite to wait for the connection;
11-15: Create a socket;
18-22: The creation of sockets and IP and port binding;
28-31: Listening port;
34-38: Receive connection;
41-46: Show welcome information;
49-54: Read client information;
57-61: echo the information to the client;
63-67: Close Socket
4.2. Running of 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)
[Code]
$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.
[/code]
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 [url=http://www.w3.org/protocols/rfc977/rfc977.html. ]http://www.w3.org/protocols/rfc977/rfc977.html. [/URL]
This document details how to chat with an NNTP server and how to use commands to accomplish tasks.
5.2.1. Connect a server
[Code]
<?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 failed\n";
Exit ();
}
else {
echo "connected\n";
$tmp = fgets ($usenet _handle, 1024);
}
?>
[/code]
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:
[Code]
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 ok\r\n") {
echo "502 Authentication error\n";
Exit ();
}
}
Select newsgroup
Fputs ($usenet _handle, "GROUP". $cfgNewsGroup. " \ n ");
$tmp = fgets ($usenet _handle, 1024);
if ($tmp = = "Authentication required for command\r\n") {
echo "$tmp \ n";
Exit ();
}
$info = Split ("", $tmp);
$first = $info [2];
$last = $info [3];
Print "A: $first \ n";
Print "Last: $last \ n";
?>
[/code]
5.2.3. Read the News
Read the News command is article, the specific use please refer to RFC977, here does not provide the routine.
6. PostScript
I thought I had written one last time, this time it will be free. A few days before the deadline, Yu Rongxian to manuscripts. Process draft hasty, inevitable mistakes, please forgive me, and pointed out.
7. Reference documents:
Liao Bin, "PHP daemon program";
The "RFC977";
Daniel solin,introduction to Socket programming with PHP;