Socket multi-user connection for help

Source: Internet
Author: User
Tags try catch
Socket multi-user connection help younger brother is working on a socket applet with flash as the client and php as the server

Now there is a problem after flash successfully connects to the server! Everything can communicate normally

But you cannot connect multiple users to the server (for example, if I open two flash files, the second connection will fail)

Php socket can solve the problem of multi-user connection


Hope to help


Reply to discussion (solution)

Has no one ever developed similar things?

Does your PHP program process HTTP requests normally? Or is it a socket server?

If it is the latter, how is your PHP program started?

You need to clarify these points first, and we will discuss them later.

Is it true socket response
Flash is always connected to php

Php
Available
Set_time_limit (0 );
Ignore_user_abort ();
Always execute

But it is still well written in java.
But I don't know java

You answered only the first of the two questions. The second question is, how is your PHP started?

If you manually pre-initiate an HTTP request to start it, you need to use a fixed port in PHP to receive and process multiple socket connection requests. This requires some skills.

If the HTTP request is initiated by FLASH, you can use different ports in PHP to receive socket connections.

In any case, the PHP program running in this way is not suitable for socket server.

Good suggestions

Use flash to start the socket server

However, I do not know the running time after startup (if it runs permanently, the server overhead will be high until it is down)
In addition, when new users enter, I need to send information to other users who have logged on before, but it is not easy to implement.

Answer your previous questions
Before starting a php game, you need to use php to connect to the server. if you cannot connect to the server, you can request it (I previously thought so)

Indeed, when each FLASH requests to start a PHP socket server, it can only serve the FLASH separately, and it is difficult to achieve the interconnection of multiple sessions.

I don't know your actual application background, so I don't know why you must use socket. if your communication method can return to common HTTP, it should be the easiest.

If you must use socket, we recommend that you consider another method. This is not to say that java is used, that is, java is used. if it is deployed in web mode, the problem is the same. PHP can also be done using CLI.

Through HTTP connection, it is through IIS, APACHE, which has a good ability to handle multiple users,

Therefore, WEBSERVICE is used whenever possible, that is, IIS, APACHE,

Therefore, when it comes to FLASH, WEBSERVICE is used,

Otherwise, if a SERVER is not properly processed, it will be blocked,

I am mainly engaged in a flash game. based on the web, I can play several people in a room.

To be able to notify other users in real time, you must use socket to achieve instant communication.

CLI has never been used. can you give me an example?
I want to know how he works and what he can do.

The key to your application scenario is "instant notification", right?

Socket can certainly achieve the goal, but it is not easy to implement, at least it will be difficult in the web container.

In fact, using HTTP persistent connections can achieve the same effect. for example, when you access Kaixin.com, there will always be an unfinished HTTP request. it will end in 30 seconds at most, but a request will be initiated immediately, this enables "Instant Notification ". For more information, see "comet persistent connections ".

(Note that the preceding 30 seconds does not mean that each notification takes 30 seconds. If there is no notification, a new connection will be used for more than 30 seconds, but if there is notification, it will return immediately)

CLI is just another startup and running method of the PHP program. it is equivalent to running an exe directly on the server, but this exe is written in PHP. Because there is no restriction on web containers, it is relatively free to use multithreading, network communication, and other functions.

Php
Available
Set_time_limit (0 );
Ignore_user_abort ();
Always execute

But it is still well written in java.
But I don't know java
How can there be ignore_user_abort ()? the php socket server should be executed under the command line, that is, the cli mentioned above, instead of being set as an http response end.
Http://devzone.zend.com/article/1086

Thank you, maquan.

Can I write an executable file with the suffix ".exe" in PHP?

Or is the file. php just started and changed?

Http://devzone.zend.com/article/1086's writing method is similar to the socket_selectin the manual.

I will try again

Thank you for your help!

The younger brother learned a lot of knowledge and some solutions that he didn't know before!

Thanks again

CLI is just another startup and running method of the PHP program. it is equivalent to running an exe directly on the server, but this exe is written in PHP. Because there is no restriction on web containers, it is relatively free to use multithreading, network communication, and other functions.


Why is there no thread limit when I run it in cli mode?
Is it equal to running the code I wrote before?

Thank you very much. you can already get online with multiple users.

It feels instant and good.

Thank you, maquan and BooJS.

Can I continue chatting after I close the post?

Want to talk to you?

As long as it is related to this topic, hehe

However, if you have other questions, you 'd better post them for your convenience. CSDN is a public place :)

I uploaded the file to the space yesterday and found that the cli operation had timed out in 30 seconds!

Then we have to write a program to guard him and run it again in cli mode when timeout is found.

Can I use try catch to monitor what is in catch when the timeout occurs?
Try {
My socket code
}
Catch (){
Request again
}

What should I do in the catch brackets?

I am not familiar with the space and do not know what management restrictions they have. The PHP running time limit can be set through set_time_limit (). The default value is 30 s.

The daemon reload method may not solve your problem well. it will make your server unstable and increase the difficulty of client development.

If you are renting a space, there will be a lot of restrictions on unusual programs. we strongly recommend that you take a closer look at persistent connections.

Okay. thank you.

The space is indeed set to 30 seconds timeout
First, let me know about persistent connections!

This requires much less environment.

I learned about comet persistent connections in one day!

It is mainly written on the php end.
Flush ();
Refresh the buffer to receive information from ajax at the front end.

At the same time, the php end does not stop working.

When the time-out period is 30 seconds, the client reconnects again.

I don't know if my understanding is correct?

That's what you mean.

However, you may be too concerned about the implementation details. In terms of concept, a persistent connection means that the server does not complete the HTTP request immediately after receiving it, but maintains the connection for a period of time (such as 30 seconds ), in this period, if a notification needs to be delivered immediately, the response content is immediately output and the connection is closed. If it is safe, return the result at the time (it is better not to wait until it is killed by the container). This gives the client a complete response, so that the client can continue the following work.

One difficulty in implementing persistent connections is how to obtain "notifications to be delivered in real time" during the waiting process, especially in web containers that lease space, simple round robin and latency must be very inefficient. it is best to use some blocking IO method.


????????????????????????????????
Based on the plug-in extension function provided by the CSDN forum, I have made a signing tool and shared it with you. we welcome Technical Exchange :)

It is difficult to know how to return New content while waiting.
Poor performance will affect instant processing.

I think so. if something needs to be returned, it reads the xml or php array created by another page (that is, reading and writing files). when the connection is initiated, record the current modification time of the file, and then return the content of the file when the modification time changes.
I don't know if this will cause some problems, such as modifying and connecting at the same time (the file was modified one second before my connection, so that information will be returned only when the next file is modified, I don't know how likely this is to happen)

I don't understand the I/O operations you mean.



I wrote a small socket example. In my blog, you can check it out.
Http://blog.csdn.net/a82168506/article/details/6307461

Thank you, brother upstairs. I have also written code for socket, which is similar to yours.

The problem is that the space is forcibly set to 30 seconds timeout (set_time_limit (0) is useless), so there is no way to see if the persistent connection can be solved!

I learned about IO.
I found this persistent connection seems to be blocking IO!

If you want to achieve non-blocking IO, where is the technique?

After testing, we found that the long connection initiated by ajax is non-blocking IO.

The browser only has restrictions on persistent connections. when two persistent connections are sent from the same browser, one cannot be connected!

Notify the customer immediately if new messages are received.

I thought of the following method:
Still use the method of reading files
First, when the page is opened, the js initiates a connection and simultaneously transmits the current modification time of the file to be read.

When the php page is reached, a new message is sent to the client when the modification time is different from the transfer time.
When the php page runs for 25 seconds, the last modification time of a file is directly returned to js. the persistent connection ends.

After js receives the modified time of the file returned by php, it re-initiates the connection and transmits the modified time of the file returned by php.

I believe this will not miss the information that needs to be notified to the client.

The above is my personal idea.

Please ask maquan to help me and share your solutions.

Thank you.

......
When the php page is reached, a new message is sent to the client when the modification time is different from the transfer time.
When the php page runs for 25 seconds, the last modification time of a file is directly returned to js. the persistent connection ends.
......
What is the program doing between the red and blue actions? If an "event occurred" occurs in 10th seconds, can you notify me in time?

The php page sleep (1) between the two actions (after a new message is returned, the connection does not end), and then checks the file modification time until the running time exceeds 25 seconds to end the connection, then a new connection is initiated by js.

This should be fine.

If it's you, how do you do it? How can I determine whether a new message needs to be returned?

When I have time, I will try flash.

First, I am afraid there is a problem with "The connection has not ended after the new message is returned". the client will think that "an HTTP Response has been fully accepted" only after the connection has ended ",. If you do not end the connection, even if you flush and so on, you only transmit the data stream to the client at most, but the client has not completed receiving and starting processing, that is to say, your notification is still not "instant ".

As for the "check for notifications" method, you should use the "polling + latency" method. Generally, this method can be used, but the "instant" and "running efficiency" are slightly different. I always think the method of blocking IO may be better. you can refer to socket_recvfrom (). The disadvantage is that the resource usage is a little higher.

There is no way to lease space, and it is subject to web containers. If you are using your own independent server, create a deamon and use multiple asynchronous IO methods.


????????????????????????????????
Based on the plug-in extension function provided by the CSDN forum, I have made a signing tool and shared it with you. we welcome Technical Exchange :)

Http://www.zeitoun.net/articles/comet_and_php/start
I found this example.

He uses a js library to achieve persistent connections and the content can be returned normally. the connection will not be terminated!

Let's take a look

I am not familiar with this database. Are you familiar with this database?

Is this true comet?

Search for materials from multiple parties
Found few references

I can only write the current level like this.

Initiate a persistent connection in js

If the php page returns a new message to js immediately and ends the connection, JS immediately initiates a new connection (before data processing) after receiving the new message)

If there is no new information in more than 25 seconds, php will end the connection and js will initiate a new connection again!

I have to use cli to run a server with socket_recvfrom (). Is it blocking I/O?
It seems that JS can also be used as a socket client to connect to the server. if multiple clients are connected at the same time, blocking occurs. do you know that the connection initiated by the client will time out? Will it be automatically connected when the socket server disconnects the previous connection?

Theoretically, if there are many clients, the real-time performance may not be guaranteed.

I seem to have misunderstood the above and found the most popular explanation.

For example, process A needs to collect A packet from the network. if there is no packet, it will wait. this is blocking.
Don't wait, do other things, wait for the package to come and then handle it is not blocked.

In this case

Initiate a persistent connection in js
If the php page returns a new message to js immediately and ends the connection, JS immediately initiates a new connection (before data processing) after receiving the new message)
If there is no new information in more than 25 seconds, php will end the connection and js will initiate a new connection again!
It is actually a blocking IO. when there is no new information, js will always process the waiting state until new information is available.

In the two segments of a communication, read operations and write operations respectively use "blocking" or "non-blocking", which are different and independent from each other.

For example, your server code: if socket_recvfrom () is used for waiting for notifications, it is "blocked", and the output HTTP Response is generally "blocked. While receiving HTTP Response on the js side, since you use AJAX, it must be "non-blocking", which is the value of AJAX, otherwise the page will become stuck to the white screen.
I have to use cli to run a server with socket_recvfrom (). Is it blocking I/O?
This is not the case. The PHP responsible for persistent connection uses socket_recvfrom () to wait for the notification data and is in the "blocking state". the notification data generated must be another common PHP program, for example, "a user logs on", which is responsible for socket_sendto ().

Theoretically, if there are many clients, the real-time performance may not be guaranteed.
The concern is not "real-time". if the communication model described above is successful, the real-time performance can always be guaranteed (of course, it depends on the network speed ). The problem is that when the number of clients is large, the resource usage will be large, including:

· Each client will continue to occupy a PHP persistent connection process resource;
· Each persistent connection process occupies one socket resource;

In general, this mode is limited to web containers and is not suitable for large-scale applications. For example, if the space service provider limits the number of concurrent HTTP connections to your website, the persistent connections may drag your entire website down. It is better to return to the "client periodic round-robin" mode, with a loss of "real-time" in exchange for "number of online users ".

I used your method to try and find a problem.

Each port can only create one socket
If I use a random port, socket_sendto will not know which ports need to be sent

Do I need to maintain a current online Port table? Is it better to save it to the database or save it as the file mode?

Use UDP broadcast. check the usage information.

Thank you for your patience.
Check the information first.

Maquan
Broadcast I have tested successfully

However, you still need to set the port for broadcasting.

I pasted my code

Php for js requests

Header ("Cache-Control: no-cache, must-revalidate"); header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); include ('config. php '); // here is $ add (IP) and $ port $ socket = socket_create (AF_INET, SOCK_DGRAM, SOL_UDP); socket_bind ($ socket, $ add, $ port ); // I try to write $ port to 0, but this will fail to be created $ port = 0; socket_recvfrom ($ socket, $ buf, 10240, 0, $ from, $ port ); echo "Received $ buf from remote address $ from and remote port $ port ". PHP_EOL; socket_close ($ socket );


Broadcast php
Include ('config. php '); $ sock = socket_create (AF_INET, SOCK_DGRAM, SOL_UDP); socket_set_option ($ sock, SOL_SOCKET, SO_BROADCAST, 1); $ msg = rand (1000,9999 ); $ len = strlen ($ msg); socket_sendto ($ sock, $ msg, $ len, 0, '2017. 255.255.255 ', $ port); // The $ port here must be the same as the $ port of the file above to receive the broadcast, however, after different clients connect, the ports must be different to successfully create a socket connection. so how can I write the connection to notify users of all ports under this IP address? Socket_close ($ sock) is notified to all users whose port is $ port );


How can I write to notify all ports?

Write socket. accept in while (1 ).

Accept is used to listen for user connection.

I don't need to connect to the user. sendto is sent to the online user based on the ip address and port.

Try socket_set_option ($ sock, SOL_SOCKET, SO_REUSEADDR, 1 );

Still not good
If the port parameter of the socket_sendto function cannot be empty, the receiver will not receive the information, that is, the information cannot be sent to all online ports at one time.

Socket_set_option ($ sock, SOL_SOCKET, SO_REUSEADDR, 1); it should be written at the receiving end, but it cannot be written either.

Can you write an example for me?

I wrote a UDP broadcast communication program last night for your reference :)

Recvfrom. php

   

Sendto. php
    

The above two PHP programs, recvfrom. php can send requests separately in multiple browser windows, which will be in the waiting state, and then send sendto in a browser window. php requests, the previous browser windows will get results at the same time.


????????????????????????????????
Based on the plug-in extension function provided by the CSDN forum, I have made a signing tool and shared it with you. we welcome Technical Exchange :)

Thank you very much.
The test is successful.
Now return to SO_REUSEADDR's explanation Reports whether local addresses can be reused.
I suddenly realized that "can I reuse the local address"
After this option is set, no bind will appear again, prompting one IP address and one port to be connected.

Just tested and found
The recvfrom. phpl statement is successfully added without this statement.
Socket_set_option ($ socket, SOL_SOCKET, SO_BROADCAST, 1 );

I think it can be deleted, because the broadcast page is sendto. php and recvfrom. php only needs to be able to reuse the local address and port.

Is that true?

I am not very clear about this.

The obvious difference between a UDP broadcast package and a normal UDP package is that the destination IP address is different ". As a socket for "listening for UDP packets", physically speaking, it will certainly be able to "perceive" broadcast and non-broadcast UDP packets, but will it "receive" broadcast packets? If you have already set this socket to the broadcast type, it will certainly be okay, but what if it is not set? Will it reject it?

I think it may be related to the specific system implementation. Although it can be used without writing, I always feel that writing is safer.

Reasonable
Calculate the Internet broadcast address and test it.

The broadcast address must have a subnet mask.

I have to ask the service provider, but the IP address alone does not seem to be enough.

I don't know if I understand it correctly. broadcast is limited to a LAN, that is, a network segment. To get out of the Internet, it is multicast (multicast), which requires the combination of routers.

I am actually broadcasting different ports of an ip address.

You can do it.

If you cannot do this, you can only maintain the port table used by one user.

I tried it.
Check if the broadcast address is incorrect.


IP address: 123.183.215.45
Subnet mask: 255.255.255.255.128
Default Gateway: 123.183.215.1

I figured it out:
123.183.215.127

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.