简体   繁体   中英

Get session in WebSocket server

I know this question has been asked before a couple of times. I followed the answers in those questions but the problem I'm facing remains.

Simply put, I want to get the username out of a session variable inside the WebSocket server. From what I understood, is that I need to get the session id and sent that over to the socket with each message. Using the id to read out the session.

Sending the session id: this.socket.send('JOIN '+sessionID);
I've made sure sessionID contains the correct id. This works fine.

This is the important part of the WebSocket server PHP:

<?php

$message = explode(' ', $message);
$command = array_shift($message);

if ($command == 'JOIN') {
    session_id(trim($message[0]));
    session_start();

    $username = $_SESSION['username'];
?>

The problem is, it still only works for the first user that joins the server. Any other user will be refused to connect because the username is already online.

Did I miss something?

Edit: I've made the server return $message[0] as well to make sure it's getting the correct session id and it returns what's expected. (It returns a different id for every user that tries to connect).

PHP keeps the sessions locked, to prevent concurrent writes, until the script ends or is manually closed with session_write_close .

And because a WebSocket server is supposed run forever, you need to do it manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM