Asked  7 Months ago    Answers:  5   Viewed   34 times

I am using web socket using PHP5 and the Chrome browser as client. I have taken the code from the site http://code.google.com/p/phpwebsocket/.

I run the server, and the client is also connected. I can chat as well. Now when I restart the server (by killing it and starting it again), the client gets the disconnected information, but automatically doesn't reconnect with server when I send the message.

How to achieve this? Like when I get the dis-connected information, should I check it and send it to JavaScript to refresh the page or reconnect?

 Answers

88

When the server reboots, the Web Socket connection is closed, so the JavaScript onclose event is triggered. Here's an example that tries to reconnect every five seconds.

function start(websocketServerLocation){
    ws = new WebSocket(websocketServerLocation);
    ws.onmessage = function(evt) { alert('message received'); };
    ws.onclose = function(){
        // Try to reconnect in 5 seconds
        setTimeout(function(){start(websocketServerLocation)}, 5000);
    };
}
Wednesday, March 31, 2021
 
Puneet
answered 7 Months ago
78

Assuming your shared hosting provider supports crontab and cron jobs (most of them do), add the following job to the crontab:

@reboot nohup php /path/to/server.php 2>&1 >/dev/null &

Additionally, you need to start it now, so simply create the following PHP file and access it once, in your browser:

<?php shell_exec('nohup php /path/to/server.php 2>&1 > /dev/null &');?>

That should do the trick. Hopefully your shared hosting provider allows execve() calls to be made. Good luck!

Wednesday, March 31, 2021
 
Bere
answered 7 Months ago
66

tl;dr:

  • with server-side routing you download an entire new webpage whenever you click on a link,
  • with client-side routing the webapp downloads, processes and displays new data for you.

Imagine the user clicking on a simple link: <a href="/hello">Hello!</a>

On a webapp that uses server side routing:

  • The browser detects that the user has clicked on an anchor element.
  • It makes an HTTP GET request to the URL found in the href tag
  • The server processes the request, and sends a new document (usually HTML) as a response.
  • The browser discards the old webpage altogether, and displays the newly downloaded one.

If the webapp uses client side routing:

  • The browser detects that the user has clicked on an anchor element, just like before.
  • A client side code (usually the routing library) catches this event, detects that the URL is not an external link, and then prevents the browser from making the HTTP GET request.
  • The routing library then manually changes the URL displayed in the browser (using the HTML5 history API, or maybe URL hashbangs on older browsers)
  • The routing library then changes the state of the client app. For example, it can change the root React/Angular/etc component according to the route rules.
  • The app (particularly the MVC library, like React) then processes state changes. It renders the new components, and if necessary, it requests new data from the server. But this time the response isn't necessarily an entire webpage, it may also be "raw" data, in which case the client-side code turns it into HTML elements.

Client-side routing sound more complicated, because it is. But some libraries really make it easy these days.

There are several upsides of client-side routing: you download less data to display new content, you can reuse DOM elements, display loading notifications to user etc. However, webapps that generate the DOM on server side are much easier to crawl (by search engines), thereby making SEO optimization easier. Combining these two approaches is also possible, the excellent Flow Router SSR is a good example for that.

Tuesday, July 27, 2021
 
Arman
answered 3 Months ago
70

My bet is that your host is blocking incoming requests to the socket. Your not supposed to run scripts like phpwebsocket within a web service (it is a server itself). This confuses a lot of people since PHP is typically used for scripting webpages, not for coding daemons.

I say this because you mentioned running the script within Xampp, and referred to your hosting service as 'webspace'.

If this is the case you will have to upgrade to a virtual server package so that you can run your own services.

Monday, August 23, 2021
 
styvane
answered 2 Months ago
84
adrlen = strlen(myname.sa_data) + sizeof(myname.sa_family);

This should be sizeof myname. The unix(7) sockets are actually defined to have a sockaddr_un like this:

       #define UNIX_PATH_MAX    108

       struct sockaddr_un {
           sa_family_t sun_family;               /* AF_UNIX */
           char        sun_path[UNIX_PATH_MAX];  /* pathname */
       };

You've given it 10+4 as the size. Which should almost work -- it doesn't count the terminating NUL byte at the end of the filename -- but even with the + 1 added, I'd feel better if you're passing in exactly the size of object you have. (Be careful of strlen(3) on strings. Almost always you need a + 1 in any expression that involves strlen(3). Funny.)

while(fgets(sendline,1000,stdin) != NULL) {
    write(sockfd,sendline,sizeof(sendline));

And here you're sending all 1000 bytes of your buffer, regardless of contents. The user might have entered one character, or one hundred, and you're sending all 1000 bytes of whatever is at that address.

Your echo method is a bit much; I'd recommend splitting the writing off into its own routine; Advanced Programming in the Unix Environment, 2nd edition (a superb book, well worth finding a copy if you expect to program Unix or Unix-like systems) has a small sweet routine I really enjoy:

ssize_t             /* Write "n" bytes to a descriptor  */
writen(int fd, const void *ptr, size_t n)
{
    size_t      nleft;
    ssize_t     nwritten;

    nleft = n;
    while (nleft > 0) {
        if ((nwritten = write(fd, ptr, nleft)) < 0) {
            if (nleft == n)
                return(-1); /* error, return -1 */
            else
                break;      /* error, return amount written so far */
        } else if (nwritten == 0) {
            break;
        }
        nleft -= nwritten;
        ptr   += nwritten;
    }
    return(n - nleft);      /* return >= 0 */
}

(See lib/writen.c in the source from the book's website.)

I haven't actually tried your code, so it's very possible none of these are the problem actually preventing your software from working :) if that's the case, leave a comment, and I'll take a closer look.

Monday, August 30, 2021
 
Yarin
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :