Not able to create websocket in swi prolog

Hi,

I am using SWI Prolog version 7.6.3. I am trying to create a websocket (server) in swipl (to better understand how to use websocket in SWI Prolog), and connect to it using opera/chrome browser (or other languages that have provisions to use websockets as clients with no success), but the browser comes back with this message:

Internal server error

goal unexpectedly failed: user:http_upgrade_to_websocket(echo,,[protocol(http),peer(ip(127,0,0,1)),pool(client(‘httpd@5000’,user:http_dispatch,(0x60000347a700),(0x600003478500))),input((0x60000347a700)),method(get),request_uri(/),path(/),http_version(1-1),host(localhost),port(5000),connection(‘keep-alive’),upgrade_insecure_requests(‘1’),user_agent(‘Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36’),accept([media(text/html,,1.0,),media(application/‘xhtml+xml’,,1.0,),media(image/webp,,1.0,),media(image/apng,,1.0,),media(application/xml,,0.9,),media(_900/_902,,0.8,)]),accept_encoding(‘gzip, deflate, br’),accept_language(‘en-GB,en-US;q=0.9,en;q=0.8’)])

Following is the simple code that was written in SWI (basically runs a websocket as server on the machine, that prints some message when data is received at server end):

NOTE: the server is started using the goal “g” in the code below, executed from the prolog console.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%

:- use_module(library(http/thread_httpd)).
:- use_module(library(http/http_dispatch)).
:- use_module(library(http/websocket)).

 :- http_handler(root(.), http_upgrade_to_websocket(echo, []), [spawn([])]).

% try hitting: http://localhost:5000 in browser.

g :- port(Port), start_server(Port).
s :- port(Port), stop_server(Port).

port(5000).
start_server(Port) :- http_server(http_dispatch, [port(Port)]).
stop_server(Port) :- http_stop_server(Port,[]).

% websocket callback function.
echo(WebSocket) :- 
    write(user_output, "in echo"), flush_output(user_output),
    ws_receive(WebSocket, Message, [format(string)]),
    ( Message.opcode == close -> true;
      (write("Message: "), write(user_output, Message.data),
       flush_output(user_output), echo(WebSocket))
    ).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Any help would be much appreciated.

Regards,
Abhijit.

Install a Web Socket Client into chrome (from the Chrome Web Store) and use that to communicate with and you should see results.
e.g. against your code:

Thank you so much Ian, for the help !

Also, I noticed that using “http://” does not work, we have to use “ws://”, maybe using http creates problems during upgrading to websocket protocol, not sure though…