Now, using php, I get data from different sockets on ip: port (using the fsockopen function). This is done to get the currently playing composition on different radio stations:

$open = fsockopen($radioip,$radioport,$errno,$errstr,'.5'); if ($open) { fputs($open,"GET /7.html HTTP/1.1\nUser-Agent:Mozilla\n\n"); stream_set_timeout($open,'1'); $read = fread($open,255); } 

As a result, the main javascript on the main page regularly accesses this php on the server. I want all this to work without unnecessary requests to the server, but using the means of the browser itself. Is it possible to make a similar function in javascript - to transfer it ip and port and as a result get the necessary data?

  • one
    Do not confuse sockets and web sockets. Connecting from a browser to an arbitrary port on sockets is impossible in principle and it will hardly be possible in the next few years. Get over it and look for workarounds to solve your problem (for example, do all the work on the server through this very php - that is, as you are doing now). - andreymal

4 answers 4

Unfortunately, any requests by the browser outside your "Origin" are possible only if there is an Access-Control-Allow-Origin in the response headers with your origin. This case is all closed for security, because if it were possible to call another AJAX from any site - a lot of bad things could be done.

Learn more about cross-domain AJAX for example here.

Websockets will not help you in this case at all, since This is a separate protocol for communication between the server and the client. And moreover, lately browsers are increasingly forcing wss (encrypted web sockets), for which besides Websockets support, SSL is also needed on this supporting server. So you especially can not do without an intermediate php script.

If you are asking this question because of the heavy load on your server - you should think about alleviating this whole business with something like the same websockets. Only not third-party servers, but your own. Which will, for example, itself, with a certain frequency, update its cache on remote servers and send information to clients with a certain frequency (or after the change). In websockets, the connection is kept and a two-way dialogue between the client and the server is possible. Thus, clients will not need to constantly refer to any page, and they will simply receive a websocket message upon sending it. This can be implemented for example on Node.js or ASP.net. In PHP, I personally have not seen such things.

    Try web sockets HTML5.

     var socket = new WebSocket("ws://IPAddress:PORT"); socket.onopen = function() { alert("Соединение установлено."); }; socket.onclose = function(event) { if (event.wasClean) { alert('Соединение закрыто чисто'); } else { alert('Обрыв соединения'); // например, "убит" процесс сервера } alert('Код: ' + event.code + ' причина: ' + event.reason); }; socket.onmessage = function(event) { alert("Получены данные " + event.data); }; socket.onerror = function(error) { alert("Ошибка " + error.message); }; 
    • I tried, one by one it gives out: Error undefined / Connection break / Code: 1006 reason: ... For example, with this radio: 93.100.61.75:8000. - federk
    • And how to make a GET request, similar to what I use in php: fputs($open,"GET /7.html HTTP/1.1\nUser-Agent:Mozilla\n\n"); ? - federk
    • one
      @federk, no way, if the target server does not support / there is no processing code for web sockets - Grundy
    • 2
      @federk, really not. This does not mean that the target server has a handler for web - sites - Grundy
    • one
      @federk, because php does not use web sockets at the same time - Grundy

    1006 CLOSE_ABNORMAL Reserved. It is not normal to indicate that it is a status code is expected.

    https://developer.mozilla.org/ru/docs/Web/API/CloseEvent

    From the Mozilov guide to CloseEvent But I assume that on the other side there is simply no websocket server, and if this is the case, then from the page (read from the browser) you will not receive any data from this socket.

    • Why then does php get data from this socket without errors? Yes, and I have not checked it before - by http you can see the necessary data - 93.100.61.75:8000/7.html . If not through a socket, is it possible to read this data from a third-party server using browser tools? - federk
    • var client = new XMLHttpRequest (); client.open ('GET', '93.100.61.75:8000/7.html' ); client.onreadystatechange = function () {alert (client.responseText); } client.send (); - Denis Epishkin
    • This code does not work. - federk
    • Wildly I apologize here a true variant var x hr = new XMLHttpRequest (); xhr.open ('GET', '93.100.61.75 : 8000/7.html ', false); xhr.send (); if (xhr.status! = 200) {alert (xhr.status + ':' + xhr.statusText); } else {alert (xhr.responseText); } - Denis Epishkin
    • VM872: 7 XMLHttpRequest cannot load 93.100.61.75:8000/7.html . No 'Access-Control-Allow-Origin' header is present on the requested resource. But there is another problem ((((They don’t want anyone to read this - Denis Epishkin

    In order for you to connect via WebSocket to that server, that server must support the WebSocket protocol , which is slightly different from HTTP.

    For all popular servers there are modules to support this protocol.

    If you do not control the remote server, then it remains to advise you to cache the data: for example, if you know that such a second t song with a duration s now plays, then next time you need to go to that server in st seconds.

    With the exception of WebSocket technology and obvious holes in browsers, you cannot connect to receive data using only JS to arbitrary ports on arbitrary IP. Imagine if that were possible!

    • That is, the answer to my question is possible? ("except" in your answer). Why then does the code in php work, which I indicated in the question, but does javascript in a similar way not want to work? With this particular example: 93.100.61.75:8000 (and any other ShoutCast radio) - federk
    • one
      Because the PHP code is executed on your server, and the JS code is on the main page in the browser. From there, all browser restrictions. If you execute the JS code on the server side, there will be no such restrictions. - sanmai