How to implement a socket server with PHP

Source: Internet
Author: User
Tags add array bind end implement socket variable time limit

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

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 then starts waiting for the message from the client.

Do not go away, the following is the complete source code:

 
 
  1. Set time limit to indefinite execution
  2. Set_time_limit (0);
  3. Set the IP and port we'll listen on
  4. $address = ' localhost ';
  5. $port = 10000;
  6. $max _clients = 10;
  7. Array that would hold client information
  8. $client = Array ();
  9. Create a TCP Stream socket
  10. $sock = Socket_create (af_inet, sock_stream, 0);
  11. Bind the socket to an Address/port
  12. Socket_bind ($sock, $address, $port) or die (' could not bind to address ');
  13. Start Listening for connections
  14. Socket_listen ($sock);
  15. echo "Waiting for connections...\r\n";
  16. Loop continuously
  17. while (true) {
  18. Setup clients listen socket for reading
  19. $read [0] = $sock;
  20. for ($i = 0; $i < $max _clients; $i + +) {
  21. if (Isset ($client [$i] [' sock '])
  22. $read [$i + 1] = $client [$i] [' Sock '];
  23. }
  24. Set up a blocking call to Socket_select ()
  25. if (Socket_select ($read, $write = null, $except = NULL, $TV _sec = 5) < 1)
  26. Continue
  27. /* If a new connection is being made add it to the client array * *
  28. if (In_array ($sock, $read)) {
  29. for ($i = 0; $i < $max _clients; $i + +) {
  30. if (Empty ($client [$i] [' sock ']) {
  31. $client [$i] [' sock '] = socket_accept ($sock);
  32. echo "New client connected $i \ r \ n";
  33. Break
  34. }
  35. ElseIf ($i = = $max _clients-1)
  36. echo "Too many clients...\r\n";
  37. }
  38. }//End If In_array
  39. If a client is trying to write-handle it now
  40. for ($i = 0; $i < $max _clients $i + +) {//For each client
  41. if (Isset ($client [$i] [' sock ']) {
  42. if (In_array ($client [$i] [' Sock '], $read)) {
  43. $input = Socket_read ($client [$i] [' sock '], 1024);
  44. if ($input = = null) {
  45. echo "Client disconnecting $i \ r \ n";
  46. Zero length string meaning disconnected
  47. Unset ($client [$i]);
  48. } else {
  49. echo "New input received $i \ r \ n";
  50. Send it to the other clients
  51. for ($j = 0; $j < $max _clients; $j + +) {
  52. if (Isset ($client [$j] [' sock ']) && $j!= $i) {
  53. echo "Writing ' $input ' to client $j \ r \ n";
  54. Socket_write ($client [$j] [' Sock '], $input, strlen ($input));
  55. }
  56. }
  57. if ($input = = ' exit ') {
  58. Requested disconnect
  59. Socket_close ($client [$i] [' sock ']);
  60. }
  61. }
  62. } else {
  63. echo "Client disconnected $i \ r \ n";
  64. Close the socket
  65. Socket_close ($client [$i] [' sock ']);
  66. Unset ($client [$i]);
  67. }
  68. }
  69. }
  70. }//End While
  71. Close the master sockets
  72. Socket_close ($sock);

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

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

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

The last argument to Socket_select () tells us that the server waits up to 5 seconds before returning a value. If its return value is less than 1, 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 new clients to the array. Lines:33 to 44.

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

The code block to be 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 various, disconnect messages, and actually disconnect-as long as the server needs to process messages. Lines:46 to the end.

The code loops through each client and checks to see if messages from them are received. If it is, get the input content. Check if this is a disconnected message based on the input, and if so, remove them from the array, otherwise it is a normal message, and then our server passes all the clients again, and one by one writes the message to them and skips the sender.

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



Related Article

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.