简体   繁体   中英

javascript websocket with ip from php variable

I am using a webserver on a raspberry pi that needs a websocket to stream data. Since it can connect to multiple wifi network or even 4G, its IP may vary. Installed on the Pi I have a script that stores its public IP in a file every 2 minutes, and sends that file to a web hosting. This allows me to locate my device if the address changes.

My question is, since I am still a newbie of javascript... I would like to read the IP with PHP and send that value to the websocket js.

My idea is:

$handle=fopen("/var/www/html/SCRIPTS/settings/ipmem.atphp","r");
$prev_ip=fgets($handle);
fclose($handle); 
$prev_ip=preg_replace("#". PHP_EOL ."|\t#", "", $prev_ip);

And then in my javascript:

<script>
    var wsip = "<?php echo $prev_ip ?>";
    ws = new WebSocket(\"ws://xxx.xxx.xxx.xxx:yyyy/ws\");

How can I insert wsip at the place of xxx.xxx.xxx.xxx without breaking everything?

I am sorry for the silly question....

Thank you a lot!

Try :

ws = new WebSocket("ws://" + wsip + "/ws");

Don't know why you use a blackslash before quotes...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM