How to Implement Socket server using PHP

Source: Internet
Author: User
Do you want to build chat applications or even games? Then, the socket server will be your first step. Once you understand the basic functions of creating a server, subsequent optimization steps will become equally simple and require

Do you want to build chat applications or even games? Then, the socket server will be your first step. Once you understand the basic functions of creating a server, subsequent optimization steps will become equally simple and require

The socket server works in this way and runs continuously to wait for the client connection. Once the client is connected, the server adds it to the customer list and waits for messages from the client.

Do not go away. The following is the complete source code:

// Set time limit to indefinite execution set_time_limit (0); // Set the ip and port we will listen on $ address = 'localhost'; $ port = 10000; $ max_clients = 10; // Array that will hold client information $ client = Array (); // Create a TCP Stream socket $ sock = socket_create (AF_INET, SOCK_STREAM, 0 ); // Bind the socket to an address/port socket_bind ($ sock, $ address, $ port) or die ('could not bind to add Ress '); // Start listening for connections socket_listen ($ sock); echo "Waiting for connections... \ r \ n "; // Loop continuously while (true) {// Setup clients listen socket for reading $ read [0] = $ sock; for ($ I = 0; $ I <$ max_clients; $ I ++) {if (isset ($ client [$ I] ['sock ']) $ read [$ I + 1] = $ client [$ I] ['sock '];} // Set up a blocking call to socket_select () if (socket_select ($ read, $ write = NULL, $ excep T = NULL, $ TV _sec = 5) <1) continue;/* if a new connection is being made add it to the client array */if (in_array ($ sock, $ read) {for ($ I = 0; $ I <$ max_clients; $ I ++) {if (empty ($ client [$ I] ['sock ']) {$ client [$ I] ['sock'] = socket_accept ($ sock ); echo "New client connected $ I \ r \ n"; break;} elseif ($ I = $ max_clients-1) echo "Too connected clients... \ r \ n ";}}// end if in_array // If a client is tryin G to write-handle it now for ($ I = 0; $ I <$ max_clients; $ I ++) {// for each client if (isset ($ client [$ I] ['sock ']) {if (in_array ($ client [$ I] ['sock'], $ read) {$ input = socket_read ($ client [$ I] ['sock '], 1024); if ($ input = null) {echo "Client disconnecting $ I \ r \ n"; // Zero length string meaning disconnectedunset ($ client [$ I]);} else {echo "New input received ed $ I \ r \ n"; // send it to the other clientsf Or ($ j = 0; $ j <$ max_clients; $ j ++) {if (isset ($ client [$ j] ['sock ']) & $ j! = $ I) {echo "Writing '$ input' to client $ j \ r \ n"; socket_write ($ client [$ j] ['sock '], $ input, strlen ($ input) ;}} if ($ input = 'eg ') {// requested disconnectsocksocket_close ($ client [$ I] ['sock ']) ;}} else {echo "Client disconnected $ I \ r \ n "; // Close the socketsocket_close ($ client [$ I] ['sock ']); unset ($ client [$ I]); }}} // end while // Close the master sockets socket_close ($ sock );

It seems like a big project at first glance, but we can break it down into several smaller parts first.

The first part is to create a server. Lines: 2 to 20.

The Code sets the variables, addresses, ports, maximum clients, and client arrays. Next, create a socket and bind it to the specified address and port.

What we need to do below is to execute an endless loop (we actually did it !). Lines: 22 to 32.

In this part of the code, the first step is to set the $ read array. These groups contain sockets of all clients and the sockets of our master server. This variable will be used later in the select statement to tell PHP to listen to each message from these clients.

The last parameter of socket_select () tells us that the server can wait up to five seconds before the return value. If the returned value is less than 1, it indicates that no data is received. Therefore, you only need to return to the top of the loop and continue waiting.

The next part of the script is to add a new client to the array. Lines: 33 to 44.

Place the new client at the end of the list. Check to make sure that the number of clients does not exceed the number that we want the server to process.

The code block to be introduced below is quite large and is also the main part of the server. When the client sends messages to the server, this code is required to handle them. Messages can be various. Disconnect messages and actually disconnect messages as long as they are messages that the server needs to process. Lines: 46 to the end.

Code loops through each client and checks whether messages from them are received. If yes, obtain the input content. Check whether this is a disconnected message based on input. If yes, delete them from the array. Otherwise, it is a normal message. Then our server passes all the clients again, and write information to them one by one, skipping the sender.

Now, let's try to create your own chat server!

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.