Jump to content

PHP websocket CLIENT help sorely needed...


PhreekOut

Recommended Posts

Hey folks! Hope your week is going well so far...

 

So I am desperately trying to create a script that will allow me to interact with the GDAX exchange websocket... I have googled until I'm about to go blind. I have setup at least 3 different 'servers' for chat programs. They all work but I cannot for the life of me figure out how to use the client side to send/receive info on the socket I need at GDAX.

 

Is this possibly a SSL issue? hmmm...

 

So.. let me tell you what I'm after, and then what I've done.

 

API docs are here: https://docs.gdax.com/#websocket-feed

Websocket address to connect to: wss://ws-feed.gdax.com

 

It is publicly accessible, or well, enough of it is to test with.

 

So, we need to establish a socket connection, push Json messages and listen for response(s).

 

I am a capable PHP coder, so I can develop the class to wrap this in... all I need from the community is a working connection that sends and accepts message packets. Just one, any one, and I'm good from there.

 

I have some simple code that was googled, and it will connect to the GDAX websocket. All messages are responded to with 404 Bad Request. Here's that:

Credit to: https://www.binarytides.com/php-socket-programming-tutorial/

if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0)))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     
    die("Couldn't create socket: [$errorcode] $errormsg \n");
}
 
echo "Socket created \n";
 
if(!socket_connect($sock , '104.16.107.31' , 80))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     
    die("Could not connect: [$errorcode] $errormsg \n");
}
 
echo "Connection established \n";

In the socket_connect function, the IP being used here was had by using gethostbyname on ws-feed.gdax.com

 

Ok, when run, I get a 'Connection established' confirmation. I am unable to test it at all unless I can successfully post a Json message to subscribe to a product, and that's where the problem lies.

 

Here's my Json data, and you can compare it to the API docs on how to subscribe (near top of Websocket docs linked above).

$message = array( 'type'=>'subscribe',
                  'product_ids'=>array( 'BTC-USD'
                                       ),
                  'channels'=>array( 'level2',
                                     'heartbeat',
                                      array( 'name'=>'ticker',
                                             'product_ids'=>array( 'BTC-USD'
                                                                  )
                                            )
                                    )
                 );
$message = json_encode( $message );

and a var_dump of $message produces:

string(124) "{"type":"subscribe","product_ids":["BTC-USD"],"channels":["level2","heartbeat",{"name":"ticker","product_ids":["BTC-USD"]}]}"

and when we do this:

//Send the message to the server
if( ! socket_send ( $sock , $message, strlen($message) , 0))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     
    die("Could not send data: [$errorcode] $errormsg \n");
}
 
fwrite( STDOUT, "Message sent successfully" . PHP_EOL );
 
//Now receive reply from server
if(socket_recv ( $sock , $buf , 2045 , MSG_WAITALL ) === FALSE)
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     
    die("Could not receive data: [$errorcode] $errormsg \n");
}

We get this response:

Socket created
Connection established
Message sent successfully
string(344) "HTTP/1.1 400 Bad Request
Date: Wed, 21 Feb 2018 10:52:29 GMT
Content-Type: text/html
Content-Length: 177
Connection: close
Server: cloudflare-nginx
CF-RAY: -

<html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>cloudflare-nginx</center>
</body>
</html>
"
NULL
Socket closed

My questions:

1. Does the Json object look correct versus the API docs on subscribing? It does to me...

2. Do I need some sort of header with POST in it along with the Json object? Not seen that anywhere, but the example script I googled had used GET to send a query to google.com

3. Is this a fail because of needing SSL? (the ws address is wss...)

4. Is this a fail because I'm not using the correct socket functions, or incorrect parameters?

5. Is this a fail because it's not possible in PHP? (beating a non-existent horse?)

 

If #5, can someone please help me find the solution in a way that will still allow me to use PHP for all the rest (because all the rest is about 90% done and two weeks invested). The 'rest' is a class that utilizes the REST API through cURL, which all works brilliantly. Problem is, they discourage banging on the REST API address to poll it. They want you to use the websocket for that.

 

Life would be complete if I could just push objects over that websocket...

 

Can you help complete my life? :happy-04:

Link to comment
Share on other sites

Right. You have identified my quest! ;)

 

In your experience with PHP, do you believe this is possible?

 

Over the years, I had to come to grips with cURL to get it to do what I needed, but over time I prevailed that one. Googling stuff for cURL, especially using/storing cookies and SSL certs, yielded lots of results. I have no problem reading up. But here, it seems there's very little geared towards my quest. 80% of results teach you to setup a websocket chat server. I've done it, and can't see what's not there - specifically, all these use basic HTTP. Any forward guidance appreciated!

Link to comment
Share on other sites

Hi, I'm the OP, this is my old PHP Freaks handle. I haven't logged on here in as PhREEEk in easily 7 years. It was quite an adventure re-activating an old hotmail account in order to get this password reset.

 

I didn't do that last night. In a state of search exhaustion on this topic, I remembered my old stomping grounds, PHP Freaks. I just created a new handle rather than try and re-activate 7 yr old accounts.

 

I logged on as PhREEk so that you could see I spent several years here doing nothing but answering questions. And not echo "hello world" threads. I no longer actively develop in PHP, but use it quite often to build my own apps and libraries.

 

As a regular Forum personality around here, I was mildly intolerant of questions that were on the complicated side, and the OP had done NOTHING to help himself. No example code, no background or research, etc. I had no problem letting them know they had some reading to do, and code to attempt, before any of us here could be of real quality help. The people who did ANY of the above? I dug in. I have provided thousands of lines of code to this very forum. Participated in many [solved] threads. The hours I spent on this forum on my own dime won't be refunded back to me on my death bed, but I'm ok with that. These forums are a place for common folks to come and get a victory. A victory that I and most other personalities around here encouraged and cheered on, hoping that person would get the PHP fire lit like it was in us, and maybe be back to these forums as more helpers. This PHP infection was a GREAT to have, and even better to pass on. It appears you created your current handle at the exact time I had need to move on, so we never met in thread that I remember.

 

But I digressed into memories.

 

Being that I have spent that time on the support side, I did not come here until I was exhausted researching, and had example code. Not feeling a re-invention of the wheel was necessary, I ended up with the above code from a search. It would connect to google.com as exampled, pass a GET message, and receive the HTML in the response. Adding in the GDAX host got me connected to I believe GDAX, so if you were me, you'd think you were really close, eh? Yeah. Been a lot of years since working with any JSON objects, so went back to school there. Got an array built that should look like the object they're expecting, and sent it. Now I'm at a 404 and came here to get some help.

 

I really don't believe I have enough time to read the entire RFC for websockets, nor have I ever had to read an entire RFC section on anything to learn to do something in PHP. I also (thankfully) do not have to read the entire Motor Vehicle code to go fight a ticket in court. RFC's have been tremendously helpful in the past to figure out very complicated REGEX's, and to tweak PHP function parameters. You offered no advice on a particular section of that RFC, just to read the RFC. If I have the proper PHP function to work with, I can very happily refer to the RFC to tweak it. I don't have that yet. That is my quest. RFC isn't going to lead me to PHP, although PHP might lead me eventually to RFC.

 

If the native PHP socket commands being used above will NOT work here, could you say so? Read the RFC? Can you tell me, my friend, am I close at ALL here, or are completely different calls needed (streaming???). I don't know, and apparently since you've good experience developing websocket servers and clients, you do.

 

You referred me to libraries. Most of these have dependencies. I do not have Composer, it is unfamiliar to me. Again, you have not answered my question in regards to a native PHP solution. If it's fact that it cannot be done without libraries that extend PHP, then can you pretty please say so? That would mean that my example code above will NEVER work, and I need to install Composer, Ratchet, or something else. But you have recommended nothing but reading. I do not actively develop, so I have no real reason to have any of these libraries or frameworks installed. But if one or a few of them are needed to get my goal above, I will download and install immediately. You provided zero guidance there. I came back to these forums when I had a need, because I remembered it to be a place where guidance was always available by people who were proud to pay forward. It's why we were here.

 

I thank you for your time, Guru kicken. I apologize for being an older gentlemen these days and not having the time to read entire documents for information I don't know I need or not. Nor do I have time to download multiple libraries and frameworks in a shotgun approach. I came here for guidance. A simple "THIS IS WHAT WORKS -->, download it, play with it, and come back to this thread if you have any problems" is kinda how I remember these forums working. But I'm an old man now. Times change.

 

Cheers,

 

PhREEEk

Link to comment
Share on other sites

I really don't believe I have enough time to read the entire RFC for websockets, nor have I ever had to read an entire RFC section on anything to learn to do something in PHP. I also (thankfully) do not have to read the entire Motor Vehicle code to go fight a ticket in court. RFC's have been tremendously helpful in the past to figure out very complicated REGEX's, and to tweak PHP function parameters. You offered no advice on a particular section of that RFC, just to read the RFC. If I have the proper PHP function to work with, I can very happily refer to the RFC to tweak it. I don't have that yet. That is my quest. RFC isn't going to lead me to PHP, although PHP might lead me eventually to RFC.

I don't know what you do and don't know, so I can't really just say "Ready this section of the RFC". I linked the whole document figuring you could either read it in full or skim it for what you need to know as you see fit. I haven't even read the entire RFC word for word, I rarely do with any manual. I look at the table of contents to see what looks relevant to my task and read those parts, which might then refer me to other parts and so on.

 

Ultimately I linked and mentioned the RFC mostly for informational purposes. In general I tend to suggest people use libraries, and if I have a particular library I like I will generally recommend it. In this case I don't so I simply linked in a search result. I don't really have the time to be researching a bunch of WebSocket libraries to find a good one to recommend to you and provide sample code.

 

While I do have some experience with the WebSocket protocol, it's relatively limited. I played with it for a few weeks back in late 2011, before the RFC was even finalized and browser support was still experimental. I haven't had a need to use it in my work so I've had no reason to keep up to date with any library development or other news related to it.

 

If the native PHP socket commands being used above will NOT work here, could you say so? Read the RFC? Can you tell me, my friend, am I close at ALL here, or are completely different calls needed (streaming???). I don't know, and apparently since you've good experience developing websocket servers and clients, you do.

PHP's socket functions would be one of the building blocks you need. It's not that they won't work, but you need more than just them. The socket functions give you the connection. Once you have the connection you have to send/receive data according to the protocol as described in the RFC. PHP has some stuff built in for popular protocols such as HTTP, FTP, and TLS but WebSocket is not one of them. You'll need your own implementation to use it.

 

You referred me to libraries. Most of these have dependencies. I do not have Composer, it is unfamiliar to me. Again, you have not answered my question in regards to a native PHP solution. If it's fact that it cannot be done without libraries that extend PHP, then can you pretty please say so? That would mean that my example code above will NEVER work, and I need to install Composer, Ratchet, or something else. But you have recommended nothing but reading. I do not actively develop, so I have no real reason to have any of these libraries or frameworks installed. But if one or a few of them are needed to get my goal above, I will download and install immediately. You provided zero guidance there. I came back to these forums when I had a need, because I remembered it to be a place where guidance was always available by people who were proud to pay forward. It's why we were here.

The second item on that list of libraries is textalk/websocket. According to it's README it functions as a client, and according to packagist it has no requirements on other PHP libraries to use it (the requires column, requires (dev) packages are not needed to use a library). They (and I) recommend using composer to install it as it makes using libraries easier, but you can also just go to their GitHub page and download a release and include it manually like in the olden days if you prefer.

 

So choose a library and see if you can make some progress. If you get stuck feel free to come back with what library you choose and your code and we can work from there.

Link to comment
Share on other sites

Thank you my friend Gk! All of those clarifications have populated the old grey matter with directions to travel.

 

I am in debt for the time you spent to expand on those questions I raised, and I do appreciate it.

 

I shall forge on, but in the meantime, if you or anyone would like to tackle this for pay, I only require a working function or 3 that accomplishes management of the connection and sending of an object with a success response. The API is public, and there is also a sandbox API, so anyone can try. I can pay in BTC or Paypal if anyone would like to try. I'd be quite happy not to become an expert on something I will likely never revisit..

 

Anyways, thanks again mate! :happy-04:

 

PhREEEk

Link to comment
Share on other sites

Hi Gk,

 

I have found success so far with Textalk.

 

I have also found that after being away from active PHP development, I now know practically nothing about PHP. :shrug:

 

I learned about Composer, installed it, etc... created a new project and it connects using Textalk's websocket.

 

So at a minimum here, your guidance has caused me to trust that installing/learning Composer would not be a waste of time or not get me anywhere.

 

This reminds me of almost any journey within my PHP travels, it's just been a long time :happy-04:

 

Thank you again for being so patient with this ol' dawg ;D  You might have to force me to water, but you ain't gotta force me to drink. I'm still thirsty, my friend! Still thirsty...

 

I'm sure I'll be back to pester some more, but until then, cheers! :pirate:

 

PhREEEk

Edited by PHP_PhREEEk
Link to comment
Share on other sites

PHP has come a long way in the last 5 years or so towards making it relevant and competitive with its "cooler" competitors like python, node and ruby. The advent of symfony2 and Composer, and the explosion of solid component libraries that followed has made it a solid choice for serverside development when it looked like its newer competition would most likely pass it by.

 

But as you've seen, composer is really the entrypoint tool you need to get these libraries at your disposal.

 

Aside from the project you found you might also want to look at https://github.com/ratchetphp/Pawl. The Ratchet server is a popular choice for developing your own custom websocket server in PHP.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.