forthrin
forthrin

Reputation: 2777

Can a WebSocket be connected to a Socket Server?

I want to implement a simple WebSocket server using PHP and nginx, and am under the following impression:

  1. Once a Websocket has gone through the "Protocol Switch" described in RFC 6455, it can communicate with any standard (non-"Web") socket server.
  2. According to the nginx manual, nginx can perform the aforementioned "Protocol Switch".

With this in mind, I tried the following simple implementation consisting of a JavaScript client, an nginx configuration, and a PHP server (see below).

Results:

Questions:

The Javascript client:

function socket() {
 
  var ws = new WebSocket("ws://socket/hello/");
  
  ws.onopen = function() {
    ws.send("Hello, World!");
  };
  
  ws.onmessage = function(event) { 
    console.log(event.data);
  };
  
}

socket();

The nginx configuration:

  server {
    location /hello/ {
      proxy_pass http://localhost:10000;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
    }   
    server_name socket;
    root socket;
  }

The PHP server:

(Implemented exactly as described in Example #1 in the PHP manual, only changing $address to 127.0.0.1.)

Upvotes: 1

Views: 1301

Answers (1)

xaxxon
xaxxon

Reputation: 19771

It can, but only if the socket server implements the websocket protocol. If you are asking if it can be used as a generic TCP or UDP socket, it cannot. Full stop.

Upvotes: 2

Related Questions