Questions about socket development

Source: Internet
Author: User
Some questions about socket development recently we have to prepare something similar to a small game server. I have played WebSocket, using a mobile phone to make a PPT remote control, you can control the WEB slides, flip them down, play them back, and then explain my things at the meeting, but it is not in-depth. you may have some questions to ask for advice:

1. loss Problem: As I learned, php starts a php script in socket, which listens to the specific port of the local machine through the socket api, then, unlike web requests, the listening ports are repeatedly run in an endless loop. similar to the example code I found, the while (true) logic to achieve continuous listening without letting the script run to the end to destroy the thread, then the second can be while (true) how many times, listen how many times, this efficiency is really no problem? It seems that only such an endless loop can be achieved. it is estimated that an endless loop will be achieved in disguise, but will it consume too much CPU in terms of frequency? initially, I don't think so, in fact, if sleep is added, even if the sleep duration is 1 second, the response may also be delayed. the user experience is definitely not good, so the estimation of high-frequency listening is also necessary. what is the conclusion of the experience?


2. process control problem: Let's not talk about high concurrency, so we don't have to worry about it in a small project for a few years. This is just to give users a real-time function. on the server side, I use the php server. when the php command starts this server script, it keeps listening, but what should I do when I close the server? It's impossible for php server. php-k stop to trigger a new thread? What should I do? if I want to maintain the upgrade or migration, how can I stop it ???
Find the PID and kill it again. However, if other http requests trigger the index under the web directory. php, it will also be a php process. if you find out how to identify which server is a bunch of php processes. pid of the php script? Okay, you can kill all the stupid methods... well, don't laugh at me. in fact, I don't want it either, because I also imagined that it would be achieved by generating a close file with a value of 1, server. every time php listens, it will first open this file to see if the value is 0. if not, it will exit... however, I/O loss is definitely irrational! Let me think about it again. I can't think of it. it's just a stupid way ............


3. memory problems: after multiple socket clients connect to the server, the server uses the previous server. the php process does not start a new process, but the original process listens to data for response. If an array is created in my listening function, when I come to a person, I append an IP address. after many people come, there will be a lot of IP addresses. it has been running slowly for a long time. it is estimated that the number of IP addresses on dozens of millions is not a problem, of course, it is necessary to delete array elements when disconnecting. this is just an example. I want to say that it seems that the processing of all clients is in the same process, and they share the memory and can access each other, for example, if user A needs to reduce user B's HP or reduce money under certain conditions (transaction functions), when the number of users increases, if you want to save these things, you can use variables. you have to find the cache, right?


4. planning problem: the requirement is a bit of a problem. for example, this is a real-time chat room. Our website is originally a common website, where the HTML code returned by common HTTP requests is displayed everywhere, however, like the 53 customer service plug-ins, this function is a real-time communication thing. almost every page has this thing, and every loading will connect to the server, sometimes a user opens a new window and the old window is not closed, there will be two connections. on the frontend side, I don't know if I can save some resources, it seems that 53 customer service won't be connected if you don't click it, but our requirements are different. it has a message reminder function. after the user enters the new page, if another user initiates a transaction request, in this small column, we have to scream at the red light, "there is a new transaction! ", This means that the client needs to listen before it can receive the message? That is, the connection starts every time you enter the page. if you do not want to bend down, the listening message is connected to another port of the server. the server can be deployed separately on a dedicated message server, after the front-end receives the message, click a pop-up box to connect to the server that is the main real-time service. this increases the complexity of the server architecture, but the load loss is estimated to be better, I understand this little trick. more distributed systems cannot be considered for the moment, just to give a good experience to a few of our users.


5. monitoring problem: the program logic is not necessarily perfect, so errors may occur and exceptions may be thrown. if the php script process fails, the connection of other new clients will fail, and a continuous listener will be required to monitor whether the connection fails. if the connection fails, exec ('php server. php ')? Is that true? According to my understanding since work, we should use the daemon process to execute the script of the daemon process. it is used to execute and call server. php to derive the server thread, yes? But how does the daemon know that the previous thread is not suspended? does it automatically generate a pid file in a directory? It seems that other software can specify to generate the program in its own directory. maybe you can use some method to get the process number itself file_put_contents.


I hope you can share your comments on the above questions. thank you!


Reply to discussion (solution)

Php does not provide the WebSocket server function, so you can only use the loop wait method to write your own code. Obviously, idling also consumes resources.
If your server is a Linux system, you can find a WebSocket server that combines php with system functions on the Internet. Open-source, it is said that the performance is good
If your server is windows, it is better not to use pure php code. Otherwise, you will encounter a lot of trouble in the future, not at the php level.

Therefore, if you really want to write your own WebSocket server, we recommend that you use node. js. at least you do not need to learn another language.
Use node. js to write a WebSocket server, which requires only 4 ~ 5 lines of code

You have basically considered other issues. solve them one by one in actual practice.

We can see a free third-party IM for users. it uses persistent connections.
If you use PHP socket to do this, it may be unrealistic to rely entirely on PHP. it should be done with system scripts...
I have never really studied...

This can be used directly. The performance is very strong. the qps of the pc quad-core persistent connection is 15 W/S, and a single server can easily support tens of thousands of clients.
Home Page: http://www.workerman.net/, there are many examples of websocket, package game
Source code: https://github.com/walkor/workerman

The answer to your question is as follows:

1 \ it is non-blocking + IO multiplexing (Epoll), the server model is similar to nginx, and the performance is very good
2 \ built-in process control, php your_file.php start-d automatically enters the daemon mode, php your_file.php stop, php your_file.php status to view the status
3 \ supports permanent persistence of variables or resources, and puts variables in the memory. of course, they can also be stored in mysql redis and other storage.
4 \ it can be deployed independently from the original web system. its GatewayWorker model naturally supports distributed deployment.
5 \ if the sub-process fails, it can be automatically pulled up. the status shows whether or not the process has crashed and how many times it has crashed. It also has statistics monitoring applications that can monitor the success rate, call curves, and time consumption of various business interfaces.

Attached websocket server demo:

 count = 4;// Emitted when new connection come$ws_worker->onConnect = function($connection){    // Emitted when websocket handshake done    $connection->onWebSocketConnect = function($connection)    {        echo "New connection\n";    };};// Emitted when data received$ws_worker->onMessage = function($connection, $data){    // Send hello $data    $connection->send('hello ' . $data);};// Emitted when connection closed$ws_worker->onClose = function($connection){    echo "Connection closed\n";};// Run workerWorker::runAll();

Change to GO and play ....

If swoole or workerman is used only, the source code is not studied. Swoole is recommended. otherwise, workerman is recommended.

This can be used directly. The performance is very strong. the qps of the pc quad-core persistent connection is 15 W/S, and a single server can easily support tens of thousands of clients.
Home Page: http://www.workerman.net/, there are many examples of websocket, package game
Source code: https://github.com/walkor/workerman

The answer to your question is as follows:

1 \ it is non-blocking + IO multiplexing (Epoll), the server model is similar to nginx, and the performance is very good
2 \ built-in process control, php your_file.php start-d automatically enters the daemon mode, php your_file.php stop, php your_file.php status to view the status
3 \ supports permanent persistence of variables or resources, and puts variables in the memory. of course, they can also be stored in mysql redis and other storage.
4 \ it can be deployed independently from the original web system. its GatewayWorker model naturally supports distributed deployment.
5 \ if the sub-process fails, it can be automatically pulled up. the status shows whether or not the process has crashed and how many times it has crashed. It also has statistics monitoring applications that can monitor the success rate, call curves, and time consumption of various business interfaces.

Attached websocket server demo:

 count = 4;// Emitted when new connection come$ws_worker->onConnect = function($connection){    // Emitted when websocket handshake done    $connection->onWebSocketConnect = function($connection)    {        echo "New connection\n";    };};// Emitted when data received$ws_worker->onMessage = function($connection, $data){    // Send hello $data    $connection->send('hello ' . $data);};// Emitted when connection closed$ws_worker->onClose = function($connection){    echo "Connection closed\n";};// Run workerWorker::runAll();


It looks good. let me try it. thank you!

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.