How to implement socket server with PHP

Source: Internet
Author: User

Want to build a chat app, or even a game? Then, the socket server will be your first step. Once you understand the basic functionality of creating a server, the subsequent optimization steps will become as simple as that.

The socket server works in such a way that it runs uninterrupted to wait for the client to connect. Once the client is connected, the server adds it to the customer list and starts waiting for messages from the client.

Don't walk away, here's the full source code:

Set time limit to indefinite executionset_time_limit (0);//Set the IP and port we'll listen on$address = ' localhost ' ; $port = 10000; $max _clients = 10;//Array that would hold client information$client = Array ();//Create a TCP Stream socket  $sock = Socket_create (af_inet, sock_stream, 0);//Bind the socket to an address/portsocket_bind ($sock, $address, $port) or Die (' Could no bind to address ');//Start Listening for Connectionssocket_listen ($sock); echo "Waiting for connections...\ r\n ";//Loop Continuouslywhile (True) {//SETUP clients listen socket for reading$read[0] = $sock, for ($i = 0; $i < $ma x_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, $except = NULL, $TV _sec = 5) < 1) CO  ntinue;/* 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"; ElseIf ($i = = $max _clients-1) echo "Too many clients...\r\n";} End If in_array//If a client is trying to write-handle it nowfor ($i = 0; $i < $max _clients; $i + +) {//For each Clientif (Isset ($client [$i] [' sock ']) {if (In_array ($client [$i] [' Sock '], $read)) {$input = Socket_read ($client [$i] [' Sock '], 1024x768), if ($input = = null) {echo "Client disconnecting $i \ r \ n";//Zero length string meaning disconnectedunset ($cli ent[$i]);} else {echo "New input received $i \ r \ n";//Send it to the other clientsfor ($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 '], $in Put, strlen ($input));}} if ($input = = ' exit ') {//Requested disconnectsocket_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 socketssocket_close ($sock); 

Well, at first glance it seems like a big project, but we can break it down into a few smaller parts first. The first part is to create the server. Lines:2 to 20.

This part of the code sets the variable, address, port, maximum client, and client arrays. Next, create the socket and bind it to the address and port we specify.

The next thing we do is execute a dead loop (actually we did it deliberately!). )。 Lines:22 to 32. The first step we make in this part of the code is to set the $read array. This array contains all the client sockets and sockets for our primary server. This variable is later used in the SELECT statement: tells PHP to listen for every message from these clients.

The last parameter of Socket_select () tells our server to wait up to 5 seconds before returning a value. If its return value is less than 1, then it means that no data is received, so just return to the top of the loop and wait.

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 we want the server to process.

The code block described below is quite large and is a major part of the server. When a client sends a message to the server, it needs the code to come forward and handle it. Messages can be of various kinds, broken messages, actual disconnects-as long as the server needs to process the message. Lines:46 to the end.

The code loops through each client and checks to see if they receive messages from them. If it is, gets the input content. According to the input to check whether this is a disconnect message, if it is to remove them from the array, conversely, it is a normal message, then our server again through all the client, and one by one write message to them, skip the sender.

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

How to implement socket server 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.