0

I created a very simple PHP socket server:

<?php

class Server{

    public $address = "127.0.0.1";
    public $port = 2000;

    public $socket;

    public function __construct(){
        $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        socket_bind($this->socket, $this->address, $this->port);
        socket_listen($this->socket, 5);
        socket_set_nonblock($this->socket);
        $this->log("Server has now started on ($this->address) : $this->port");

        $this->doTicks();
    }

    public function shutdown(){
        $this->log("Shutting down...");
        socket_close($this->socket);
        exit(0);
    }

    public function doTicks(){
        while(true){
            if(!$this->tick()){
                $this->shutdown();
            }
            usleep(10000);
        }
    }

    public function tick(){
        //blah, read socket
        return true;
    }

    public function log($message){
        echo $message . "\n";
    }
}

Now I am very confused on the javascript side implementation of this. My goal is too make a real-time notification delivery system.

My question is:

  • How can I connect to this socket javascript (to be able to read it)
  • Can clients write to sockets, or only servers?

This is my first time with sockets, and nothing I search is giving me a clear answer to these questions.

  • its missing a whole lot of code, essentially your just starting a socket there its not going to do anything read/respond/peer stack. You might be better off looking at using a lib like https://reactphp.org/ which then your just need to do the js side https://stackoverflow.com/questions/12407778/connecting-to-tcp-socket-from-browser-using-javascript – Lawrence Cherone Sep 24 '17 at 18:33
  • @LawrenceCherone thank you I got it working now :D – captincrunch Sep 24 '17 at 18:42

0 Answers0