How to implement socket Server _php tutorial with PHP

Source: Internet
Author: User

How to implement socket server with PHP


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:

 
 
  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 = ten;
  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 '], 1024x768);
  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 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're going to do is execute a dead loop, actually, we did it on purpose! )。 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!

http://www.bkjia.com/PHPjc/1029282.html www.bkjia.com true http://www.bkjia.com/PHPjc/1029282.html techarticle How do I use PHP to implement a socket server that wants to build a chat app, or even a game? Then, the socket server will be your first step. Once you know the base for creating the 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.