问题
I'm working on a little project to make a 1v1 chat system. I wanted to work on a project where I could put Server-Sent Events
to good use. It's been working pretty well, but recently I have been making some changes to the code so that in general the chat would be more efficient.
When I have the event source running I run into a weird issue. When I try to go to any other PHP page that has session_start() it doesn't load.
My event source script looks something like this:
<?php
session_start();
require "connect.php";
require "user.php";
header("Content-Type: text/event-stream\n\n");
header('Cache-Control: no-cache');
set_time_limit(1200);
$ms = 5000;
//SOME MORE VARIABLES HERE
while (1) {
echo "data: SSESSION " . $_SESSION["conversation" . $_GET["id"]];
echo "\n\n";
/*CHAT SCRIPT HERE*/
ob_flush();
flush();
usleep($ms * 1000);
}
?>
What the session should return is the number of rows for the conversation. It does indeed.
If I go to test.php
:
<?php
session_start();
echo $_SESSION["conversation121643"];
?>
While the Server-Sent Event
is running, this page just continues loading until I cancel the event.
I tried using the ob_flush
function, but that doesn't fix anything.
I have no clue why i'm having this issue. And I hope there is a fix for it.
回答1:
PHP has exclusive lock around session. Only one process at a time can use it. This is usually unnoticeable because PHP processes start and end quickly, but with SSE you're keeping the session open forever and all other PHP processes will wait until SSE process ends.
You can execute session_write_close()
to release the session to other processes.
来源:https://stackoverflow.com/questions/17621175/pages-with-session-start-dont-load-when-server-sent-event-is-running