Vijay Sharma
Vijay Sharma

Reputation: 831

I am not able to send message on web socket by using php

My URL:"http://provabextranet.com/es2al/test2_chat.php". I want to send message on this URL. I used all most all the examples but am not able to send. I used host:'184.154.48.162' and port:9001. Its a web socket using JS. and i just want send by php not by JS. please help me out.

`<?php
echo "<h2>TCP/IP Connection</h2>\n";
$service_port = 9001;
$address = gethostbyname('www.provabextranet.com');
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
} else {
    echo "OK.\n";
}
echo "Attempting to connect to '$address' on port '$service_port'...";
echo socket_connect($socket, $address, $service_port) or die( socket_strerror(socket_last_error()));
socket_strerror(socket_last_error($socket)) . "\n";
$in = "HEAD / HTTP/1.1\r\n";
$in .= "Host: www.provabextranet.com\r\n";
$in .= "Connection: Close\r\n\r\n";
$out = '';

echo "<br>Sending HTTP HEAD request...<br>";
echo socket_sendto($socket, $in, strlen($in),0,$address,$service_port) or die( socket_strerror(socket_last_error()));
echo "OK.\n";
}
socket_close($socket);
echo "OK.\n\n";
?>`

OutPut:

TCP/IP Connection

OK. Attempting to connect to '184.154.48.162' on port '9001'...1 Sending HTTP HEAD request... 1O K. Closing socket...OK.

And Other Program:

`<?php
$host = '184.154.48.162';
$port = 9001;
$local = "184.154.48.162"; 
$data = 'hello world!'; 
    $head = "GET / HTTP/1.1"."\r\n".
            "Upgrade: WebSocket"."\r\n".
            "Connection: Upgrade"."\r\n".
            "Origin: $local"."\r\n".
            "Host: $host"."\r\n".
            "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ=="."\r\n".
            "Sec-WebSocket-Version: 13"."\r\n".
            "Content-Length: ".strlen($data)."\r\n"."\r\n";
    $sock = fsockopen($host, $port, $errno, $errstr, 2);
    fwrite($sock, $head ) or die('error:'.$errno.':'.$errstr);
    $headers = fread($sock, 2000);

    fwrite($sock, "hello" ,5) or die('error:'.$errno.':'.$errstr);
    echo socket_strerror(socket_last_error());
    $wsdata = fread($sock, 2000); 
    $retdata = trim($wsdata,"\x00\xff");
        $contents = "";
    while (!feof($sock)) {
        echo $contents .= "<br>".fgets($sock, 4096);
    }
    fclose($sock);
?>`

Output: Success

Upvotes: 1

Views: 142

Answers (1)

Vijay Sharma
Vijay Sharma

Reputation: 831

my english is not good but understand what am try to tell.. actually for this you need to open a port that you using, **

study first how to open port then only you can send or receiver msg

**. And if you bind then you don't have to use bind or connect for same ip:port. you have store in array and check when its sending something in array for ,to know is already bind or not if bind then no need to bind again, otherwise bind with ip:port

Upvotes: 0

Related Questions