PHP socket programming

Source: Internet
Author: User
Tags nntp nntp server
PHP socket programming author: Jiu Long information/Zhang Xiaogang <br/> socket programming, generally using c or c ++. Especially in web application development, perl is often used by Jiu Long information/Zhang Xiaogang

Socket programming generally uses c or c ++. Especially in web application development, perl is often used to implement sockets. In addition, using php for socket programming is also an option. Is Php competent? Of course. Php is a high-quality web application development language. many of its features can handle a large number of tasks, and network programming is no exception.

1. understand socket
Mail, ftp, telnet, name, and finger services are provided on a dedicated public Port. by connecting to these ports, the customer program can access these services. This is similar to real life-when you need to clean your clothes, you need to find a dry cleaners; when you need to get money, you need to go to the bank, and so on. In addition to ports dedicated to specific servers, computers also have other ports for programmers to create their own servers.
The port is generally numbered. by specifying the port number of the server, the client program can connect to the port. Each server or Port must have a specific protocol. to enable the customer's request to be understood and responded, the customer must form a customer request in a server-specific manner.
A Socket is the end of a two-way communication connection between two programs running on the network. The general meaning of Socket is natural or manual plug-in, such as power plug-in of household appliances.
The client program can write a request to the Socket. the server will process the request and return the result to the client through the Socket.
Socket is an underlying connection. The client and server communicate through the byte stream written to the Socket. They must have a common protocol, that is, the language used to transmit information through Socket must be protocol-effective.

2. Socket connection establishment process
The procedure is as follows: (connection-oriented)
Client process

Socket ()
|
Bind ()
|
Listen () |
|
Accept () <---------------- connect ()
|
Recv ()/send () <----------> send ()/recv ()

3. Php basic socket call:
3.1. basic socket call
Create a socket -- socket ();
Bind the local port -- bind ();
Establish a connection -- connect (), accept ();
Listener port -- listen ();
Data transmission-send (), recv ();
Multiplexing of input/output -- select ();
Close socket -- closesocket ()
3.2. socket call provided by php:
Accept connection -- accept connect ()
Bind ()
Close socket-close ()
Initialize connection-connect ()
Listener port-listen ()
Read socket-read ()
Create socket-socket ()
Write socket-write ()

4. basic applications
4.1. a simple TCP server
1 #! /Usr/local/bin/php-q
2
3 4 /*
5 * We don't want any time-limit for how the long can hang
6 * around, waiting for connections:
7 */
8 set_time_limit (0 );
9
10/* Create a new socket :*/
11 if ($ sock = socket (AF_INET, SOCK_STREAM, 0) <0)
12 {
13 print strerror ($ sock). "n ";
14 exit (1 );
15}
16
17/* Bind the socket to an address and a port :*/
18 if ($ ret = bind ($ sock, "10.31.172.77", 10000) <0)
19 {
20 print strerror ($ ret). "n ";
21 exit (1 );
22}
23
24 /*
25 * Listen for incoming connections on $ sock.
26 * The '5' means that we allow 5 queued connections.
27 */
28 if ($ ret = listen ($ sock, 5) <0)
29 {
30 print strerror ($ ret). "n ";
31}
32
33/* Accept incoming connections :*/
34 if ($ msgsock = accept_connect ($ sock) <0)
35 {
36 print strerror ($ msgsock). "n ";
37 exit (1 );
38}
39
40/* Send the welcome-message :*/
41 $ message = "Welcome to my TCP-server! N ";
42 if ($ ret = write ($ msgsock, $ message, strlen ($ message) <0)
43 {
44 print strerror ($ msgsock). "n ";
45 exit (1 );
46}
47
48/* Read/Receive some data from the client :*/
49 $ buf = '';
50 if ($ ret = read ($ msgsock, $ buf, 128) <0)
51 {
52 print strerror ($ ret). "n ";
53 exit (1 );
54}
55
56/* Echo the received data back to the client :*/
57 if ($ ret = write ($ msgsock, "You said: $ bufn", strlen ("You said: $ bufn") <0)
58 {
59 print strerror ($ ret). "n ";
60 exit (1 );
61}
62
63/* Close the communication-socket :*/
64 close ($ msgsock );
65
66/* Close the global socket :*/
67 close ($ sock );
68?>

Row 8th: use set_time_limit to set the program execution time to be infinite and wait for the connection;
11-15: Create a socket;
18-22: bind the created socket to the IP address and port;
28-31: listening port;
34-38: accept connections;
41-46: displays welcome information;
49-54: Read client information;
57-61: display information to the client;
63-67: disable socket
4.2. TCP server running
The above tcp server requires php to be compiled into the cgi interpretation method, and -- enable-sockets is added during compilation.
If you have compiled the program to run in cgi interpretation mode, but the projects listed using the php-m command do not have sockets, you need to re-compile php. When these requirements are met, you can run the server.
Start the server:
./Filename. php
Then you can use telnet to log on.
Telnet 10.31.172.7710000
Your terminal will display:
Trying 10.31.172.77...
Connected to 10.31.172.77.
Escape character is '^]'.
Welcome to my TCP server!
Enter Something and press enter:
Hello
You said: Hello
Connection closed by foreign host

You can also modify the program to make it look like the phpmanual example. the connection is closed only when the client inputs "quit.

5. other applications
5.1. chat room applications
5.1.1. common chat room implementation
Generally, the implementation of the chat room is usually to use the framework page, and then refresh one of the frameworks used to display the conversation content using html, for example:

This method will cause the browser to continuously send requests to the server. when there are a large number of requests, the server operation efficiency will be reduced. Such chat rooms obviously have design drawbacks.
However, if you use socket to implement chat rooms, the situation is different.
5.1.2. use socket to implement chat rooms
The chat room we will discuss is very simple, just a practical implementation.
It is a client/server structure program. First, start the server, and then the user uses the client to connect. the advantage of the client/server structure is that it is fast, but the disadvantage is that when the server is updated, the client must also be updated.

Initialize the server so that the server enters the listening status: (The following is only the implementation principle and does not involve specific programs)

$ Socket = socket (AF_INET, SOCK_STREAM, 0 );
// First create a socket. The family is AF_INET and the type is SOCK_STREAM.
// AF_INET = ARPA Internet protocols uses the TCP/IP protocol family
// The SOCK_STREAM type provides sequential, reliable, and full-duplex connection based on byte streams.
// Because there is only one protocol in this protocol family, the third parameter is 0

 
Bind ($ sock, $ address, $ port)
// Bind the socket with an address.

Listen (sockfd, MAX_CLIENT)
// After the address is bound, the server enters the listening status.
// MAX_CLIENT is the total number of clients that can establish connections at the same time.

After the server enters the listen status, wait for the client to establish a connection.

Before establishing a connection, the Client also needs to initialize the connection:

$ Socket = socket (AF_INET, SOCK_STREAM, 0 ))
// Similarly, the client also sets up a socket with the same parameters as the server.

Connect ($ socket, $ address, $ service_port)
// The client uses connect to establish a connection.

When the client initiates a new connection request to the Server, the server uses accept to accept the connection:

Accept_connect ($ sock)
// Accept returns a new file descriptor.

After the server enters the listen status, because multiple users may request a connection, the program needs to perform operations on these users at the same time and implement information exchange between them. This is called I/O multiplexing.
The method of I/O multiplexing is not described in this article. if you are interested, please refer to relevant books.

5.2. a web-based newsgroup browser
In php, you can use fsockopen to open a tcp socket connection.
Int fsockopen (string hostname, int port [, int errno [, string errstr [, double timeout])
For more information about how to use this function, see The php Manual.
To access the newsgroup service, you must use a Protocol called NNTP, that is, Network News Transfer Protocol.
This protocol has a special RFC description, which is located at http://www.w3.org/protocols/rfc977/rfc977.html.
This document details how to talk to the same nntp server and how to use commands to complete the task.
5.2.1. connect to a server
$ Login server = "news.php.net ";
$ Export Port = 119;
$ Required timeout = 10;

// Open a socket
If (! $ Timeout)
// Without timeout
$ Usenet_handle = fsockopen ($ container server, $ container port );
Else
// With timeout
$ Usenet_handle = fsockopen ($ response server, $ response port, & $ errno, & $ errstr, $ response timeout );

If (! $ Usenet_handle ){
Echo "Connexion failedn ";
Exit ();
}
Else {
Echo "Connectedn ";
$ Tmp = fgets ($ usenet_handle, 1024 );
}
?>

5.2.2. dialog with the server
We have already connected to the server. what should we do if we want to select 10 recent news records from a news group?
RFC977 indicates that the group command is used to select a newsgroup:
GROUP ggg

// $ Login user = "xxxxxx ";
// $ CfgPasswd = "yyyyyy ";
$ Optional newsgroup = "alt. php ";

// Identification required on private server
If ($ login user ){
Fputs ($ usenet_handle, "authinfo user". $ your USER. "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 Authentication errorn ";
Exit ();
}
}

// Select newsgroup

Fputs ($ usenet_handle, "GROUP". $ Using newsgroup. "n ");
$ Tmp = fgets ($ usenet_handle, 1024 );

If ($ tmp = "480 Authentication required for commandrn "){
Echo "$ tmpn ";
Exit ();
}

$ Info = split ("", $ tmp );
$ First = $ info [2];
$ Last = $ info [3];

Print "First: $ firstn ";
Print "Last: $ lastn ";
?>

5.2.3. read news
The command for reading news is article. for details about the usage, refer to RFC977. no routine is provided here.

6. postscript
I thought I wrote an article last time, so this time I can skip it. Just a few days after the submission date, Yu Rong gave me an appointment. The process draft is too hasty to avoid mistakes. please forgive me and point out.

7. references:
Liao Bin, "php daemon programming";
W3c, RFC977;
Daniel Solin, Introduction to Socket Programming with PHP;

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.