Jonatha Suh
Jonatha Suh

Reputation: 195

Sending data from javascript to php websocket

I have a php websocket written as:

$socket = socket_create(AF_INET, SOCK_STREAM, 0);
socket_bind($socket, '127.0.0.1', 8080);
socket_listen($socket);

I run this by php server.php on command line and runs continuously. I am trying to send data from a javascript script to this server. Is it possible? Things I have tried is creating a websocket connection from javascript and using websocket.send(JSON) but it doesnt seem to register in the server.php (or im not sure how to correctly grab the data from the javascript send). Is it possible to send? If so, how could I send?

Upvotes: 0

Views: 1267

Answers (2)

jfriend00
jfriend00

Reputation: 707298

webSocket is a specific protocol running on top of TCP. It has a specific frame format that must be used in order to communicate with another endpoint using webSocket. It is not just a plain TCP socket as it looks like you are using. Here's a reference document on the webSocket protocol if you want to see how it works.

In fact, webSocket connections are initiated with an http request which are then "upgraded" to the webSocket protocol.

If you're using PHP, you can get a module that speaks the webSocket protocol and use that. I'm not a PHP developer myself, but I hear that Ratchet is a popular way to support webSockets with PHP and there are several others. Here's a related StackOverflow question on webSocket support for PHP.

Upvotes: 1

Neil Villareal
Neil Villareal

Reputation: 637

You might be interested to this http://www.sanwebe.com/2013/05/chat-using-websocket-php-socket

Upvotes: 0

Related Questions