0

here is my code and this work perfectly it sends the message. but server.php doesnt receive it. now if I use javascript and html5 and send to ws://localhost:8000/instantchat/server.php it works of course. I am guessing I need to specify the server.php file on the socket_connect function somehow. If I change localhost with the ws URL or just with a direct path it will fail to look up host so it wont connect. any ideas how to do this? I did go to php dot net and looked pretty much everywhere on google. Any help please will be greatly appreciated

<?php

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";

//Connect socket to remote server
if(!socket_connect($sock , 'localhost' , 8000))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);

    die("Could not connect: [$errorcode] $errormsg \n");
}

echo "Connection established \n";

 $message = array( 'action' => 'chat_text' , 'user_id' => '4' , 'chat_text' => '');
 $message = json_encode($message);

//Send the message to the server
if( !socket_send ( $sock , $message , '55' , 0))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);

    die("Could not send data: [$errorcode] $errormsg \n");
} else echo "Message send successfully \n";
nodejsj
  • 535
  • 1
  • 5
  • 14

1 Answers1

0

The code you've written here is not correctly negotiating a WebSocket connection. You will need* to use a WebSocket library to do that; see "Is native PHP support for Web Sockets available?" for a list of PHP WebSocket libraries.

*: While it's technically possible to write a client yourself based on the specification, it's rather complex, making it inadvisable to do so yourself unless you have some very unusual requirements.

Community
  • 1
  • 1
  • thanks Duskwuff. Been banging my head against the wall for a couple of hours now trying to figure this out, although it makes a connection and sends to the file now. (figured that out) but the message received cannot be used it returns an error every step of the way – nodejsj Sep 30 '14 at 19:01