PHP socket programming
Solden text programming, generally C or C . Special in Web application development, a socket is often used. In addition to this, it is also a choice to use PHP. Can PHP be qualified? of course can. PHP is a high-quality web application development language. Many of his characteristics can handle numerous tasks, and network programming is no exception. 1. Understand the socket Mail, FTP, Telnet, Name, and Finger These services are available on a dedicated public port. By connecting to these ports, the client can access these services. This is similar to real life - when you need dry cleaning clothes, find a dry shop; when you need money, go to the bank, and so on. In addition to the ports dedicated to a specific server, there are other ports that allow programmers to create their own servers. The port is generally numbered, and the client can connect to the port by the port number of the specified server. Each server or port must have a specific protocol, in order to allow the customer to be able to understand and respond, the customer must form a customer request in such a manner. Socket is one end of the two-way communication connections running on the network. The general meaning of the word Socket is a natural or artificial socket, such as a power jack of a household appliance. The client can write a request to the Socket, and the server will process this request, and then return the result to the customer via Socket. Socket is a bottom layer connection. The client and server communicate via the byte stream written to the socket. They must have a common agreement, that is, the language used when transmitting information through sockets must be good.
2. Socket Establishing the process of connecting the process of establishing the following: (Connection-Oriented) Server Circular CLIENT SOCKET () Socket () | | bind () bind () | | () | | | aCEPT () <- ---------------- CONNECT () | | Recv () / send () <---------> send () / rec () 3. PHP Basic socket call: 3.1. Basic socket call Create a socket - Socket (); Bind the native port - Bind (); establish a connection --connect (), accept (); listening port - -Listen (); Data Transmission - Series (), Recv (); Input / Output Multi-Demo - Sense (); Close Solder --closeSocket () 3.2. PHP Sockets provided: Accept Connection - Accept Connect () Binding Port - Bind () Close Skin --close () Initialization Connection --Connect () Listening Port - Listen () Read Sockets-Read () Create Socket - Socket () Write Skin-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 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 Street. "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 EX IT (1); 22} 23 24 / * 25 * Listen for Incoming Connections On $ SOCK. 26 * The '5' Means That Weilow 5 Queued Connections. 27 * / 28 IF ($ RET = Listen ($ SOCK, 5)) <0) 29 {30 Print Street. "N"; 31} 32 33 / * Accept incoming connections: * / 34 IF ($ msgsock = accept_connect ($ sock) <0) 35 { 36 Print Street. "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)) <0) 43 {44 Print Street ($ 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 Streerror ($ 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 Street ($ 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?> Chapter 8: Using the set_time_limit setting program execution time is unlimited to wait for the connection; 11-15: Create a socket; 18-22: Bind the created socket with IP and port; 28-31: Listening port; 34-38: Accept connection; 41-46: Show welcome information; 49-54: Read client information; 57-61: Review information to the client; 63-67: Close the socket 4.2. TCP server runs on this TCP server running requires PHP compiling into CGI interpretation, and compiles- -ENABLE-SOCKETS. If you have compiled into a CGI interpretation, you have no sockets listed using the items listed using the command php -m, indicating that you need to recompile the PHP. When these requirements are reached, you can run this server to start the server: ./filename.php You can log in with Telnet. Telnet 10.31.172.77 10000 Your terminal will appear: TRYING 10.31.172.77 ... connection to 10.31.172.77. escape character is '^]'. Welcome to my tcp server! then enter some things, and enter: hello you SAID: Hello Connection Closed by Foreign Host You can also modify this program, let it like the example on phpManual, only when the client enters "quit", close the connection. 5. Other Applications 5.1. Chat Room Application 5.1.1. Common chat room Implementing the usual use of a general chat room is to use the frame page, and then refresh one of the frames for displaying the contents of the conversation. For example: Using this method can cause the browser to constantly issue a request to the server side, when there is a lot of requests It will make the server running efficiency decrease. Such chat rooms are obviously designed for disadvantage. But if you use socket to implement a chat room, the situation is different. 5.1.2. Using Socket to implement chat room We have to discuss very simple, just an principle implementation.
It is a client of a Client / Server structure, first starting server, then users use clients to connect. The advantage of the Client / Server structure is fast, and the disadvantage is that when the server is updated, the Client must be updated. Initializing Server, make Server enters Monitor status: (The following is just the implementation principle, does not involve specific programs) $ socket = socket (AF_INET, SOCK_STREAM, 0); // Building a socket, the family is AF_INET, the type is SOCK_STREAM. // AF_INET = ARPA Internet Protocols Using the TCP / IP protocol // sock_stream type provides order, reliable, byte-based full-duplex connections. // Since there is only one protocol in the protocol family, the third parameter is 0 bind ($ SOCK , $ address, $ port) //, then bind this socket with an address. After the address binding, Server enters the listening state. // max_client is the total number of clients that can be established simultaneously. After the server enters the Listen state, wait for the client to establish a connection. Client End To establish a connection, you also need to initialize the connection: $ socket = socket (AF_INET, SOCK_STREAM, 0)) // The same, the Client also creates a socket first, the parameters are the same as Server. Connect ($ socket, $ address, $ address, $ Service_port) // Client Use Connect to create a connection. When the request is sent to the server, Server uses accept to accept the connection: Accept_connect ($ SOCK) // Accept Returns a new file descriptor. After the server enters the Listen state, the program needs to be operated on these users, because there may be multiple user requests to connect, and the program needs to be operated simultaneously and implements information exchange between them. This is referred to as I / O multi-channel multiplexing techniques. The method of I / O multiplexing technology is not the content you have to describe this article. If you are interested, please refer to the relevant books. 5.2. A web-based newsgroup browser can open a TCP Socket connection int Fsockopen (String Hostname, int port [, int errno [, string errstr [, double timeout]]) for use in PHP (String Hostname, INT Port [, int errno [, string errstr [, double timeout]]) Please refer to the PHP manual. Access the newsgroup service, you need to use a protocol called NNTP, namely NetWork News Transfer Protocol. This protocol has a dedicated RFC description, which is located at http://www.w3.org/protocols/rfc977/rfc977.html. This document describes how to do the same NNTP server dialog and how to use the command to complete the task.
5.2.1. Connect a server PHP $ cfgserver = "news.php.net"; $ cfgport = 119; $ cfgtimeout = 10; // Open a socket if (! $ Cfgtimeout) // WITHOUT TIMEOUT $ usNet_Handle = fsockopen ($ cfgServer, $ cfgPort); else // with timeout $ usenet_handle = fsockopen ($ cfgServer, $ cfgPort, & $ errno, & $ errstr, $ cfgTimeOut); if (! $ usenet_handle) {echo "Connexion failedn"; exit ();} else {echo "connected"; $ TMP = fgets ($ usnet_handle, 1024);}?> 5.2.2. Talk to the server in front, we have connected with the server, if we want to be from one What should I do in the news group? RFC977 pointed out that choosing a newsgroup using group command: group ggg Php // $ cfguser = "xxxxxx"; // $ cfgpasswd = "yyyyyy"; $ cfgnewsgroup = "alt.php"; // identification request on private server IF ($ cfguser) {FPUTS ($ USENET_HANDLE, "Authinfo User". $ cfguser. "n"); $ TMP = FGETS ($ USENet_Handle, 1024); FPUTS ($ usnet_handle, "authinfo pass". $ cfgpasswd. "N "); $ TMP = FGETS ($ usnet_handle, 1024); // Check Error IF ($ TMP! =" 281 okrn ") {Echo" 502 Authentication Errorn "; exit ();}} // select newsGroup FPUTS ($ Usenet_handle, "group". $ cfgnewsgroup. "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. The command to read the news reading news is Article, please refer to RFC977 for specific usage, this is not provided. 6. Postscript I thought it would be exempt from the last time. Not a few days in the date of delivery, Yu Rongfu is about a draft. The contributation is inevitable, it is wrong, please forgive me, and point out.