WebSocket connection failed

Theerayuttu2 years ago

I tried to create sample html page to connect websocket for get data real-time updates gps location. but still not work it error cannot connect to ws.

WebSocket connection to 'ws://MyIP:8082/api/socket' failed:

please help advise me do I have to fix it or what should I do? (I'm a coding beginner)

html code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>try traccar api</title>
  </head>
  <body>
    <script src="jquery-2.2.2.min.js" charset="utf-8"></script>
    <script type="text/javascript">
     

    $.ajax({
            url: "http://MyIP:8082/api/session",
            dataType: "json",
            type: "POST",
            data: {
                email: "xxxxxxxxx@xxxxx.com",
                password: "xxxxxx"
            },
            success: function(sessionResponse){
                console.log(sessionResponse);
                openWebsocket();
            }
        });

        var openWebsocket = function(){
            var socket;
            socket = new WebSocket('ws://MyIP:8082/api/socket');

            socket.onclose = function (event) {
                console.log("WebSocket closed");
            };

            socket.onmessage = function (event) {
                console.log(event.data);
            };

        socket.onerror = function (event) {
                console.log(event);
            };
        };
  
    </script>
  </body>
</html>
Theerayuttu2 years ago

result in Console log:

{id: 1, attributes: {…}, name: 'admin', login: null, email: 'xxxxxxxx@xxxxx.com', …}
administrator: true
attributes: {activeMapStyles: 'locationIqStreets,osm,carto,googleRoad,googleSatel…,openTopoMap,googleHybrid,autoNavi,ordnanceSurvey', selectedMapOverlay: 'openSeaMap', notificationTokens: 'rsferifdsfodFrtfKOEDdfksfds4Oif99dAPA91bHYSp0BUotbEkwJaZVPEOC…5KyQtruL3qj2tocynF2FgWs................'}
coordinateFormat: null
deviceLimit: -1
deviceReadonly: false
disableReports: false
disabled: false
email: "xxxxxxxx@xxxxx.com"
expirationTime: null
fixedEmail: false
id: 1
latitude: 0
limitCommands: false
login: null
longitude: 0
map: null
name: "admin"
password: null
phone: null
poiLayer: null
readonly: false
twelveHourFormat: false
userLimit: 0
zoom: 0
[[Prototype]]: Object

WebSocket connection to 'ws://MyIP:8082/api/socket' failed: 

Event {isTrusted: true, type: 'error', target: WebSocket, currentTarget: WebSocket, eventPhase: 2, …}
isTrusted: true
bubbles: false
cancelBubble: false
cancelable: false
composed: false
currentTarget: WebSocket {url: 'ws://MyIP:8082/api/socket', readyState: 3, bufferedAmount: 0, onopen: null, onerror: ƒ, …}defaultPrevented: false
eventPhase: 0
returnValue: true
srcElement: WebSocket {url: 'ws://MyIP:8082/api/socket', readyState: 3, bufferedAmount: 0, onopen: null, onerror: ƒ, …}
target: WebSocket {url: 'ws://MyIP:8082/api/socket', readyState: 3, bufferedAmount: 0, onopen: null, onerror: ƒ, …}
timeStamp: 433.40000009536743
type: "error"
[[Prototype]]: Event
WebSocket closed
Anton Tananaev2 years ago

My guess the problem is that you're trying to connect to some external host. Ideally you should have the API on the same host as your HTML page.

Theerayuttu2 years ago

Thank you Anton, I have traccar API and HTML page on the same server. actually on the url code I have used same IP server

url: "http://18.143.xxx.xxx:8082/api/session"
socket = new WebSocket('ws://18.143.xxx.xxx:8082/api/socket');

Is it correct? or use localhost instead.

Theerayuttu2 years ago

Session already response 200
Response Cookies:

JSESSIONID=node0yamsvz1p6tjy1e4z1.......

but still error connect ws

failed: Error during WebSocket handshake: Unexpected response code: 503
Anton Tananaev2 years ago

Why do you need full URL in your ajax request if it's on the same host?

Theerayuttu2 years ago

Sorry, I have refer and get the HTML code from this issue: https://github.com/traccar/traccar/issues/2551
I'm trying to try and write the code accordingly. to see how it can fetch values from WebSocket.
I'm beginner coding. please advise me or is there a simple example? Thank you again.

jose juan2 years ago

Hi Anton, I have a question is it possible to connect to websokect from an external host?

Anton Tananaev2 years ago

Never tried. It might be possible, but the easiest option is just to proxy.