Code Monkey home page Code Monkey logo

php-websockets's Introduction

PHP WebSockets

A WebSockets server written in PHP.

This project provides the functionality of an RFC-6455 (or Version 13) WebSockets server. It can be used as a stand-alone server, or as the back-end of a normal HTTP server that is WebSockets aware.

In order to use PHP WebSockets, you must have the ability to arbitrarilly execute scripts, which almost always means having shell access to your server, at a minimum. It is strongly encouraged that you have the ability to configure your machine's HTTP server. It is strongly discouraged to allow arbitrary execution of scripts from a web interface, as this is a major security hole.

To use:

Do not place the files in your web server's document root -- they are not intended to be ran through a web browser or otherwise directly accessible to the world. They are intended to be ran through PHP's Command Line Interface (CLI).

The main class, WebSocketServer, is intended to be inherited by your class, and the methods connected, closed, and process should be overridden. In fact, they are abstract, so they must be overridden.

Future plans include allowing child processes forked from the controlling daemon to support broadcasts and to relay data from one socket in a child process to another socket in a separate child proccess.

Browser Support

Broswer Name Earliest Version

Google Chrome 16

Mozilla Firefox 11

Internet Explorer 10

Safari 6

Opera 12.10

Android Browser 4.4

Note: Current browser support is available at http://en.wikipedia.org/wiki/WebSocket#Browser_support under the RFC-6455 row.

For Support

Right now, the only support available is in the Github Issues ( https://github.com/ghedipunk/PHP-Websockets/issues ). Once I reach my $250/mo Patreon reward level, I'll be able to maintain support forums for non-core code issues. If you'd like to support the project, and bring these forums closer to reality, you can do so at https://www.patreon.com/ghedipunk .

php-websockets's People

Contributors

blondie101010 avatar evolve32 avatar ghedipunk avatar segfaulty avatar xaraknid avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-websockets's Issues

$this->connected($user)

Gratulation, your websocket was the only one I actually was able to run...
Playing around, I noticed an error occurring every time I tried to send ($this->send($user, 'hallo!')) something to greet a connected user. Seems, that handshaking is necessary before sending, so perhaps you move $this->connected($user) from line 86 to line 188.
Lorenz

Script sleep at sending response to users

Hi thanks for your project !

I have a problem with this script, when my clients are more than 15-20 people server sleep at sending back message and cant handle a lot messages.... and i don't know whats wrong with this !

output
sourcecode

What is your email address?

OK, in all fairness to myself, I did scour the Internet for your contact information, and came up empty. I just became your project's first Patreon sponsor and would like to reach out to you via email to discuss my project involving PHP-Websockets. You can find my email here: http://www.phpexperts.pro/

Task: Overall conceptual design of new version of the WebSocket server library

Note: This is a living document. Please make suggestions to change it while this task is open.

Primary goals

Implement a fully RFC 6455 compliant WebSocket server library that

  • Is easy to use
  • Has full unit test coverage
  • Is secure by default
  • Allows extensive, modular customization

Considerations

  • Minimum requirements: PHP 5.5. It could very well be fully compatible with earlier versions of PHP, but we won't guarantee it.
  • Non-blocking IO by default. This is obvious with the network IO, but also applies to reading from file, such as when pulling data from a PHP session.
  • Unit testing is best when using OOP design principles that are often overlooked (and often mis-implemented): Separation of Concerns, Dependency Injection, single purpose classes, code to the interface not the implementation.
  • Users should be able to change nearly every aspect of the library by implementing the appropriate interface and injecting it into the application, from the network IO, event loop, message queues, down to how different apps behave.
  • We want to limit our external dependencies down to just what ships with a sane Linux distro's PHP, and have advanced options that require external dependencies be optional. That is, the PECL module event, which depends on libevent can be shipped with the core library, but the default event loop would be a while loop with socket_select(). If we decide to use dependency injection, we probably can't use a mature DI container like Dice, because DI would be integral to the library (or at least integral to allowing uesrs to add their own modules and extend functionality) and we can't have an external dependency on Dice since it doesn't ship with PHP.

Initial Design

Key components

  • Network IO
  • Event loop
  • Messages (Inbound and outbound)
  • Message Queues (Potentially many queues, but at least an inbound and outbound one)
  • Client Connection (Formerly WebSocketUser class)
  • Message Router
  • Apps

Network IO

Directly handles sending and receiving messages. Responsible for setting up the socket(s), including any TLS settings. Not responsible for the WebSocket framing and deframing.

Network IO Interface:

Note: PHP 7.0 function syntax for clarity of documentation of scalar types and return type, but actually implemented to be PHP 5.5 compatible

public function sendMessage(string $framedMessage, resource $clientSocketResource) : void;
public function getPacket(resource $clientSocketResource) : string; // a packet may not be a full WebSocket message (IP fragmentation, among other reasons), or may be multiple messages (Nagle's Algorithm, etc.)
Dependencies
  • Message queues

Event Loop

Controls process flow depending on IO and timing events

Event Loop Interface
public function run() : void;
Dependencies
  • Network IO
  • Message Router

Inbound Message

Holds a single message and a reference to the sender's socket resource.

Inbound Message Interface
public function getMessage() : string;
public function getSender() : ClientConnection;
Dependencies
  • ClientConnection

Outbound Message

Holds a single message and its destinations.

Outbound Message Interface
public function setMessage(string $message) : void;
public function setDestinations(array $connections) : void;
public function setDestination(ClientConnection $connection) : void;
public function addDestinations(array $connections) : void;
public function addDestination(ClientConnection $connection) : void;
Dependencies

None

Router

Routes messages between network IO queues and client applications.

Router Interface
public function registerApplication(Application $application, string $path) : void;
public function dispatchMessage(Message $message) : void;
Dependencies
  • Outgoing and incoming message queues

Application

A client program

Application Interface
public function tick() : void;
public function onMessage(Message $message, Connection $connection) : void;
public function onOpen(Connection $connection) : void;
public function onClose(Connection $connection) : void;
public function onError(Connection $connection) : void;
Dependencies
  • Router

Client Connection

Keeps track of a WebSocket client

Client Connection Interface
public function getResource() : resource;
public function getHeaders() : array;
public function getSessionValue(string $key) : (any type); // May block if another script has that session file open.
public function setSessionValue(string $key, (any type) $value); // May block if another script has that session file open.

// Not convinced on these right now, but they match the [client side API](https://www.w3.org/TR/websockets/#the-websocket-interface).
public function getReadyState() : int; // CONNECTING = 0; OPEN = 1; CLOSING = 2; CLOSED = 3;
public function getExtensions() : array;
public function getProtocol() : string;
Dependencies

None

(More may come later, but I don't want to leave this page open over the weekend and risk having a power outage cause me to lose this work in progress.)

Getting error on client side.

Error: InvalidStateError: DOM Exception 11

Hello,

I am testing code and just check html page.
shows me,
WebSocket - status 0

If I send msg then
Error: InvalidStateError: DOM Exception 11

Need quick help

The web socket cannot be closed by client

At the client side if I try to close the web socket. it does not close immediately. There is a bug in websocket.php

Instead of

if ($user->hasSentClose)
{
     $this->disconnect($user);
}

It should be

if ($user->hasSentClose)
{
     $this->disconnect($user->socket);
}

Priorities for 2016

First priority: Finish TLS support in the Legacy branch, merge to Master.

High priorities:

  • Unit testing in new development branch.
  • Autobahn testsuite.
  • Minimum Viable Product for new development branch.
  • Project site. (Download zip/tarball, project announcements, documentation wiki, reference implementations (chat, simple games, CMS features), support forum... Start simple, of course.)

Normal priorities:

  • Parse cookies from headers
  • Expose PHP session
  • Add support for multiple apps (Jailed connections. I.e., app registered to "/echo" can not access connections that request "/chat")
  • Add support for different network IO models (i.e., have code that handles TLS and non-TLS connections through Berkeley sockets, stream sockets, or a user defined means). Explicitly disallow users from changing which network IO model to use, once we start listening for new connections, and explicitly disallow multiple IO models to be active at the same time.
  • Add support for binding to multiple TCP/IP sockets (Multi-NIC, IPv4 + IPv6 at the same time, multiple port numbers, etc., see below)
  • Add the ability to choose different event loops, such as libevent (http://docs.php.net/event) or a while loop around socket_select(), as well as allow user-defined loops.
  • Re-optimize everything. (Optimizing is good. Pre-optimizing isn't. Who cares if a defined constant is microseconds faster than a local static variable that never gets altered if you're waiting whole seconds for a series of SQL requests that can be streamlined?)

Potential features:

  • Allow apps to specify whether they're accessible through a specific TCP/IP socket.
  • Composer support

Recurring:

  • During planning stages for any feature, ensure that setting up a basic server is as easy as possible, secure by default (especially if dealing with TLS), and that extensions and features can be intuitively configured.
  • Periodically during development, ensure that setting up a basic server is easy, secure, and configuration is intuitive.
  • During unit testing, double check that things are easy, secure, and configurable.
  • During code review, check that configuration is intuitive, basic servers remain secure by default, and that a person can set up the reference echo server with little more than SSH access, a PHP version that comes by default from their distro, and an FTP client.

Ideas to consider:

  • CMS/Framework projects (chat in Drupal, Symfony, replacements for popular AJAX features).
  • eCommerce platform plugins. (Especially Magento. If any platform could benefit from misappropriating WebSockets as an AJAX-on-steroids feature, it's Magento. Plus, they'll appreciate the TLS for PCI certification.)
  • Package management system (obviously far more involved than the base server itself)

Please add any priorities that I missed, or feature requests, in the comments below. This first post will be regularly updated.

Alternative for the current slow filling $effectiveMask

This is used inside applyMask() use to be able to decode what the client send to browser.

I try to optimize the code, i will pull the complete job once I fix an issue a have with something.

I made this benchtest quickly to test speed of different method to replace the current one where it become very slow, the larger the payload size are. I post here for the help of other person to test it and confirm what should be the method to replace the current one.

warning ! in it current config it take 25sec for the current method to process 64K payload of processing 10K frames.
you can change at the start of the file the size of payload
here the file https://github.com/Xaraknid/PHP-Websockets/blob/master/bench.php

allmost of the time str_repeat win. here my output
time total / min / max / avg / nbloop ( inside a while ) / over (to be remove from effectiveMask) /
check (integrity $effectiveMask match the payload size) / rps (potential request per second) / faster by ( number of time faster of slowest method)

Testing current
Testing optimized............
Testing optimizedv2.......
Testing str_repeat..................
Testing str_pad..................
array(5) {
  [0]=>
  array(10) {
    ["total"]=>
    float(0.08144474029541)
    ["name"]=>
    string(10) "str_repeat"
    ["min"]=>
    float(6.9141387939453E-6)
    ["max"]=>
    float(8.4877014160156E-5)
    ["nbloop"]=>
    int(0)
    ["over"]=>
    int(-1)
    ["check"]=>
    int(64123)
    ["avg"]=>
    float(8.144474029541E-6)
    ["rps"]=>
    float(122782.63720565)
    ["faster by "]=>
    float(310.68131520708)
  }
  [1]=>
  array(10) {
    ["total"]=>
    float(0.11458611488342)
    ["name"]=>
    string(11) "optimizedv2"
    ["min"]=>
    float(9.7751617431641E-6)
    ["max"]=>
    float(9.4175338745117E-5)
    ["nbloop"]=>
    int(14)
    ["over"]=>
    int(-1413)
    ["check"]=>
    int(64123)
    ["avg"]=>
    float(1.1458611488342E-5)
    ["rps"]=>
    float(87270.608748484)
    ["faster by "]=>
    float(220.82395460759)
  }
 [2]=>
  array(10) {
    ["total"]=>
    float(0.12534499168396)
    ["name"]=>
    string(9) "optimized"
    ["min"]=>
    float(1.0967254638672E-5)
    ["max"]=>
    float(8.2015991210938E-5)
    ["nbloop"]=>
    int(14)
    ["over"]=>
    int(1413)
    ["check"]=>
    int(64123)
    ["avg"]=>
    float(1.2534499168396E-5)
    ["rps"]=>
    float(79779.813023672)
    ["faster by "]=>
    float(201.8697252418)
  }
  [3]=>
  array(10) {
    ["total"]=>
    float(2.190878868103)
    ["name"]=>
    string(7) "str_pad"
    ["min"]=>
    float(0.00018501281738281)
    ["max"]=>
    float(0.00060606002807617)
    ["nbloop"]=>
    int(0)
    ["over"]=>
    int(0)
    ["check"]=>
    int(64123)
    ["avg"]=>
    float(0.0002190878868103)
    ["rps"]=>
    float(4564.3783166609)
    ["faster by "]=>
    float(11.549410330287)
  }
  [4]=>
  array(9) {
    ["total"]=>
    float(25.303359031677)
    ["name"]=>
    string(7) "current"
    ["min"]=>
    float(0.0023021697998047)
    ["max"]=>
    float(0.0070538520812988)
    ["nbloop"]=>
    int(16031)
    ["over"]=>
    int(1)
    ["check"]=>
    int(64123)
    ["avg"]=>
    float(0.0025303359031677)
    ["rps"]=>
    float(395.20444647215)
  }
}

Unable to run in live server

Working fine in local sever.But when uploaded in live server,the server is running :

xxxx@xxxx [~/public_html]# php -q testwebsock.php
Server started
Listening on: 0.0.0.0:9006
Master socket: Resource id #6

but client.html giving error:
WebSocket - status 0
Disconnected - status 3

changed host in client page:

var host = "ws://xxx.com:9006/echobot"; // tried with site name
also
var host = "ws://IP:9006/echobot"; // tried with IP too

but nothing is working.I am new with socket.So please let me know if I am missing anything.
Thanks in advance

Handshake will fail if sent with more than one packet.

The handshake will never happens if the handshake headers is sent with more than one packet.

Normal browser will close the connection after their internal timeout.

Also the handshake need a timeout server side otherwise can lead to malicious user to overload server with multiple open connection will cause ressource exhaustion.

Passing autobahn testsuite

I highly recommend that you take time making this library pass autobahn testsuite.

First it'll help find some odd bugs.
Second it'll help to respect standard of RFC 6455.

1-8 and 10 : is about basic protocol
9 : benchmark purpose
12 and 13 : is about compression.

Also most probably will help to speed up the library. I tested it with your library and my version.

All test are done with php7 on localhost. I added support of stream library the libevent are not there because they are not yet supported on php 7. Time are in seconds.

autobahn testsuite without 9 -12 -13
...eventloop...   total time    - server side time - calls
ghedi socket    53.894512891769 - 0.2540876865387  - 1053
xarak stream    11.52151799202  - 0.12486124038696 - 1442
xarak socket    11.546305894852 - 0.16052651405334 - 1343
xarak libev     11.529824018478 - 0.20058488845825 - 1329

here the result : https://drive.google.com/file/d/0B5H5z7SEgVa4cUNGSnlLSUJJM1k/view?pref=2&pli=1

For binary support I add ->onbinary event for apps.

Composer support

Is Composer/Packagist support planned?

composer require ghedipunk/php-websockets would be a lot simpler than git cloning, etc.

Cannot telnet to socketserver

Hi,

I have a question that is it possible for me to telnet to the newly started socket server to be able to test it from my terminal?

I currently set it up to listen on 127.0.0.1:21001 and when I try to telnet to it from another terminal it fails:

$ telnet 127.0.0.1:21001
telnet: 127.0.0.1:21001: Name or service not known
127.0.0.1:21001: Unknown host
$ telnet ws://127.0.0.1:21001
telnet: ws://127.0.0.1:21001: Name or service not known

Is it even possible to use telnet for WebSockets?

Thank-you in advance.

Secure websocket - Internet Explorer

Hi there,

We've developed a Facebook application that needs secure websockets.

We're using Nginx as a reverse proxy which takes incoming secure websocket connections and routes them internally as non-secure.

Your PHP-Websockets library really works well with Chrome and Firefox but not at all with Internet Explorer.

Just wondering if you know of a way to make Internet Explorer accept secure websocket connections under this configuration?

Thanks
Wynne

server closing connection not cleanly

It's seem the server never send any close opcode neither close status code.

if the close handshake was respected and all goes normal server should send close opcode with 1000 as status code or without status code be sent i should see 1005 status code instead I allways receive 1006 stand for abnormal closure mean the transport was kill prior to sending close opcode.

That applied either if client request the closing handshake first or server closing the connnection for any reason it's seem he to slam the connection down.

You can see status code on client side even see if the websocket connection was close cleanly.

socket.onclose   = function(msg) { 
console.log(msg.code);
console.log(msg.wasclean);   
log("Disconnected - status "+this.readyState);
};

Maybe mimicking the browser with is readystate closing state applied after an endpoint send close opcode in this state you could skip all remainning data on the wire untill you recieve close opcode response.

As you can reconnect the websocket automaticaly without any user intervention but I want only to reconnect when the connection really close abnormal.

opcode extracted wrong

In extractHeaders() on line 420:

'opcode' => ord($message[0]) & 8 + ord($message[0]) & 4 + ord($message[0]) & 2 + ord($message[0]) & 1,

this should be

'opcode' => ord($message[0]) & 15,

Now opcodes are interpreted by the server correctly. However now disconnect messages are handled incorrectly, when it receives a opcode 8 (disconnect) $willClose gets set to true, and the function quits prematurely (according to the spec, disconnect message MAY can contain a body and therefore should be interpreted by the server. You can do this by changing line 350 in deframe():

            case 8:
                $user->hasSentClose = true;
                break;

and on line 67 in __construct:

                                        if ($message = $this->deframe($buffer, $user)) {
                                            $this->process($user, utf8_encode ($message));
                                            if($user->hasSentClose) {
                                                $this->disconnect($user->socket);
                                            }
                                        }

( there's also another process() function above that needs the if statement). Now the server will correctly handle disconnection events.

The problem is now process() gets called on a disconnect, which is what we want, but the deframe process buffers it with some funny characters. It maybe another bug in the deframe() function, I simply fixed this with if($user->hasSentClose) return;, but again that's a hack.

Also I tested the mbstring fix: it works great :)

Fixes for firefox & another hidden bug

You have to change line 153 in websockets.php to get it working firefox 11:

    //FIX for firefox (headers can contain keep-alive, Upgrade)
    if (!isset($headers['connection']) || strpos(strtolower($headers['connection']), 'upgrade') === FALSE) {

This is because firefox sends a keep-alive header as well.

There's also an issue with the extractHeaders() function, sometimes the header length will be extracted wrong. Causing it to over read the buffer and the frame will return an incorrect string. Right now sockets only accept UTF-8 so it will cause the connection to fail.

Suggestion

You state on the main page that you are trying to achieve a $250/mo Patreon reward level, why don't you add a link on the main page for donations via PayPal, etc.? This might help reach the $250/m level sooner.

MB_STRLEN and headers['length']

Today I download this code. I try with the client.html and the testserver but when I send messages with special charachter, like "é, ő, ű" and so on, the
$headers['length']
and the
mb_strlen($this->applyMask($headers,$payload))
differs.
The $headers['length'] shows the correct length, but the MB_STRLEN shows greater! and than its return false so the message doesn't recieved by the server :(

Testing needed: new tick() method

Probably very straightforward, but just in case I made a bonehead mistake...

New tick() method added. Blocking timeout changed from indefinite to 1 second.

Passed initial smoke test. Would appreciate others taking a look, too.

Updated branch dev-legacy.

Refresh (reconnect) from IE crashes the server

HI,

I tested the provided testwebsock.php with client.html and observed this on Internet Explorer 11:

  • I ran the server srcript, testwebsock.php, on an apache server on ubuntu.
  • I ran the client.html on Internet Explorer 11. The client successfully connected to the server. I could send a message and received the echo.
  • When I clicked the "Refresh" button on IE, the server crashed, printing out this message: "Socket error: Connection reset by peer"

Any suggestion on why this might happen or how to fix/investigate?

Thanks

How to ping a client

I see that there is some parts of code, that deals with pinging.
I want to disconnect and remove from active clients list a client, that has not sent a message or ping request for more than 30 seconds, but I don't see, how to achieve that.
In addition to that, how to determine lag or ping time between server and client?

dohandshake miss 2 fields and 1 check.

One of the missing field are "port" an optional if you use default port.

The other is required because it's need to be check :

"http" must be equal or higher than 1.1. If a client have a version lower should return http error code 505 - HTTP Version not supported.

Another thing is the return handshake in case of client fail to send a conform websocket handshake. Like bots sending that :

GET / HTTP/1.1
Host: x.x.x.x:port
Connection: Keep-Alive

or any other malformed websocket headers
The server respond with that :

HTTP/1.1 426 Upgrade Required
Sec-WebSocketVersion: 13

I know security by obscurity is not bullet proof but giving info on a silver platter on other hand...

Discussion of new major version

Based on maturing as a developer, I feel that there are some fundamental architectural changes to the project that would benefit other developers and projects.

While the current implementation is technically sound, and can easily handle a large number of clients using the same WS application, I think that we could benefit from scaling outwards as well.

For instance, if a site wants multiple WS applications specified through different request URIs or through different Host headers (in the style of web server Virtual Hosts), then as it stands, all code is loaded into a single instance, and connection-based routing to the correct appliance must happen on all network events.

Additionally, as currently implemented, the application blocks until it receives a network event. If, for example, data in a database that should be sent to all clients gets updated from outside of our application, then we would have to wait until a client sends a message to the server before the server can then unblock, check state, then update all clients.

Further, there's no support for multiple servers, such as clustered environments or environments replicated across regional data centers. Granted, this is a fringe feature, but one that I believe is possible and should be a reasonable goal.

And, while this "bug" doesn't exist in the vanilla implementation (it's far too simple for this bug to even exist simply because the "process()" method is abstract), it's easy for bugs to be introduced to have user information bleed over between connections. I want to avoid this, and make such bugs harder to be introduced.

However, I'm not the only user on this project any more, and my plans will break all current applications that have already implemented this WS server, requiring those applications to be rewritten if they attempt to upgrade.

I do plan on continuing to maintain the current version of this WS server through development of the new branch and for a reasonable time after the new version is released, but wouldn't be adding any new features (not like I had been adding any new features before, so nothing lost there).

So, this issue is one big happy feature request and architectural discussion thread. Feel free to comment.

when i use nohup for connecting socket, it does not create connection with db.

how to create temporary connection?

  • ssh root@IP
  • password
  • cd /home/maindomain/public_html/domain/socket/PHP-Websockets-master
  • php -q maypage.php

In this connection, socket connectivity with the database remains stable and working fine.
But in production as I can not put a local connection I need to make socket connection permanently so I am using following thing for permanent connection :

  • nohup php -q mypage.php

but in this condition socket does not make connection with database.

Problem – I need to hold persistent data on socket so that I can share with other devices. How can we achieve this.

PHP-Websockets in SSL

I'm using the PHP-Websockets with SSL.
The client connection is: var host = "wss: //127.0.0.1: 9000 /";

As I boot the server to meet SSL call?

New feature discussion: Pre-frame bulk messages

Framing a message is a time consuming operation. If there are multiple messages with the same contents, frame them once.

(Maybe make a message class? Definitely going to do for the next version... not sure if we'll implement it like that on the legacy branch, since it bends the paradigm too far.)

How to send Custom client Id in server.php file?

Hello,
I am planning to connect this websocket with my database, so I am putting my database code in server.php file. but i did not want to send and autogenerated clientId instead i want to send clientId registered in database so i want to know how to send a client id from index.html to server.php?

Feature Request: Parse cookies from headers

Cookies are available in the HTTP headers sent during the handshake. Parse the cookies out of them, especially session cookies.

Bonus: Add a way to get the session data into the user object, if the developer wants them.

New feature discussion: TLS

I have decided to implement TLS (wss://) in the server using the built-in PHP OpenSSL functions.

This will require much testing and much review. I know I'm good, but I also know that hubris is the cause of many security holes. Simply put, I simply refuse to trust myself when it comes to encryption, even if I know I'm doing everything right. (I've had good teachers when it comes to encryption. I don't trust them, either.)

So, this be the discussion thread for implementing TLS.

Latest Safari - WebSocket

Hi,

First, great work and thank you for sharing!
With the latest Safari 7.0.6 I still can't open a websocket connection, can you confirm?

Thanks
Jérôme

Not working in Chrome 19 and up

For some strange reason the server is not accepting connection from the recent Chrome on Windows. Still works nicely with Firefox though.
What is more strange, it is working nicely on Linux with the recent Chrome. I tried to dig for some information, and I guess the problem related to the frame masking, and from now "A server must not mask any frames that it sends to the client."
Any solution for this?

socket_write not as robust as originally thought

While working on other issues this morning, found that socket_write() is not as robust as I'd originally thought.

function signature:

int socket_write(socket_handle $socket, string $buffer, int $length);

Depending on network conditions and the size of the buffer, it may write less than $length bytes to the socket.

Thus, implementing a _send() and _rawSend() pair of methods: _send() will add the message to a send buffer, and _rawSend() will process the buffer, sending as much of each message as possible. _rawSend() will be implemented in _tick(), as well as called by _send() immediately after putting the message in the buffer.

Socket error: Connection reset by peer, when Nmap

(great job btw!)
I'm still on the example. Launching testwebsock.php works fine, but asa a nmap scan occured, a RST packet is received and the connection fail fatally. Dropping data.

Server started
Listening on: 0.0.0.0:9000
Master socket: Resource id #6
Client connected. Resource id #7

Socket error: Connection reset by peer

nmap 192.168.0.10 -p9000

Handshake can fail

I force the handshake request to be sent over multiple packet and if client did that It will fail.

websocket.php line 79

 if (!$user->handshake) {
$tmp = str_replace("\r", '', $buffer);
if (strpos($tmp, "\n\n") === false ) {
continue; // If the client has not finished sending the header, then wait before sending our upgrade response.
}
$this->doHandshake($user,$buffer);
} 

should be replace with

if (!$user->handshake) {
  if ($user->handlingPartialPacket) {
    $buffer=$user->partialBuffer . $buffer;
    $user->handlingPartialPacket=FALSE;
    $user->partialBuffer='';
  }
  //security buffer overflow if buffer exceed 512 bytes without "\n\n" close the connection
  if ( strlen($buffer)  > 512 ) {
    $handshakeResponse = "HTTP/1.1 400 Bad Request"; 
    socket_write($user->socket,$handshakeResponse,strlen($handshakeResponse));
    $this->disconnect($user->socket);
  }
  else {
    $tmp = str_replace("\r", '', $buffer);
    if (strpos($tmp, "\n\n") !== false ) {
      // If the client has finished sending the header, otherwise wait another call before sending our upgrade response.
      $this->doHandshake($user,$buffer);              
    }
    else {
      //store partial packet to be analysed in next call
      $user->partialBuffer=$buffer;
      $user->handlingPartialPacket=TRUE;
    }
  }
} 

I add a security to prevent too large handshake headers request. As a normal client request should be around 256 bytes.

want to change response.

Hey,
Code is working fine for me, what i am getting is the string in response which i am sending in request.
Now i want to change my response, how can i achieve this.

I hope it will make sense....

minimum php version a question to ghedipunk

I would like to know what the lowest php version you want php-websockets to support?

As I see in developement you use "namespace" that mean php 5.3 required.

I currently working on optimization of the current code and I think I find a way to meet the requirement you want for this project. Keep core code, allow multiple method library and allow dev patch in different space. That way user patch will be untouched if we upgrade the core code.

That way I will be able to pull a version optimized with support to default ( socket ) , libev eventloop and a spot for making libevent too for windows server.

But all this will required to make the minimum php version to 5.4 using traits. Is this correct for you ?

Socket get disconnect after certain period of time.

Hi,
Now i am working with the major socket based project where i have used this code. No doubt it working extremely good. But there is one problem that is i am starting socket from terminal that is from local, so that it get disconnected if my pc gets down or internet connection get lost.
What i want to do is, that i want open socket connection permanently i mean if anybody hit that url than socket should get started.
There should be no need to start it first from my terminal.
Can i do it in any way.?

currently i am stating my socket like -

canopus@canopus-K54C:~$ ssh root@MY-IP
root@MY-IP's password:
Last login: Mon Dec 7 14:28:26 2015 from static-3254654654.SP.com
root@SERVER-PATH
[email protected] [PHP-Websockets-master]# php -q FILE-NAME.php
Server started
Listening on: MY-IP:9000
Master socket: Resource id #6

Sometimes connection hangs, when working with mb-string extension

I used to test the server with original php-cli.ini settings, which did not have the mb-string extension included.
Then when I included the mb-string extension, the connections hang from time to time, without any obvious reasons. I found out tha the mb_strlen($payload) was made on the masked payload, which depending on the mask, causes the mb_strlen-function to be confused and return a false length, which indicates the server that it received a partial message and waits for it.
I changed this line of code in function deframe, line 390 from
if ($headers['length'] > mb_strlen($payload)) {
to
if ($headers['length'] > mb_strlen($this->applyMask($headers,$payload))) {

Could you please check and afterwards update the code, since I am not familiar with git.
Thanks Martin

multiple instances of websocketserver

Hi,
I have question. Can I create multiple instances of server like:
$server1=new server("127.0.0.2","9001");
$server1=new server("127.0.0.3","9002");
$server1=new server("127.0.0.4","9003");
and connect via web browsers to each server?
And also is it possible to connect via this web servers to mysql database ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.