Failed error during websocket handshake unexpected response code 200

When I tried to establish websocket communication between AngularJS app and Spring Boot I'm getting the error: Error during websocket handshake - Unexpected response code: 200. Here is my JS cod...

When I tried to establish websocket communication between AngularJS app and Spring Boot I’m getting the error: Error during websocket handshake — Unexpected response code: 200.

Here is my JS code:

function run(stateHandler, translationHandler, $websocket) {
    stateHandler.initialize();
    translationHandler.initialize();

    var ws = $websocket.$new('ws://localhost:8080/socket'); // instance of ngWebsocket, handled by $websocket service

    ws.$on('$open', function () {
        console.log('Oh my gosh, websocket is really open! Fukken awesome!');  
    });

    ws.$on('/topic/notification', function (data) {
        console.log('The websocket server has sent the following data:');
        console.log(data);

        ws.$close();
    });

    ws.$on('$close', function () {
        console.log('Noooooooooou, I want to have more fun with ngWebsocket, damn it!');
    });
}

And here is my Java code:

WebsocketConfiguration.java

@Override
public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry)
{
    stompEndpointRegistry.addEndpoint("/socket")
        .setAllowedOrigins("*")
        .withSockJS();
}

@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
    registry.enableSimpleBroker("/topic");
}

WebsocketSecurityConfiguration.java

@Override
protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
    messages
        // message types other than MESSAGE and SUBSCRIBE
        .nullDestMatcher().authenticated()
        // matches any destination that starts with /rooms/
        .simpDestMatchers("/topic/tracker").hasAuthority(AuthoritiesConstants.ADMIN)
        .simpDestMatchers("/topic/**").permitAll()
        // (i.e. cannot send messages directly to /topic/, /queue/)
        // (i.e. cannot subscribe to /topic/messages/* to get messages sent to
        // /topic/messages-user<id>)
        .simpTypeMatchers(SimpMessageType.MESSAGE, SimpMessageType.SUBSCRIBE).denyAll()
        // catch all
        .anyMessage().denyAll();
}

Does anyone have an idea how to fix this problem?
Thank you in advance!

I’m using load balancer in front of an aws ec2 instance(I will have more in future). In this ec2, I have a website being served by nginx on port 80, a nodejs app listening on 8080 and the websocket on 4555.

My nginx.conf has rules to pass the requests based on location / as you can see:

server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  localhost;
        root         /var/www/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

       #try_files $uri $uri/ @rewrite;
       # location @rewrite {
       #    rewrite ^/(.*)$ /index.php?param=$1;
       #}

    location /api {
               proxy_pass http://127.0.0.1:8080;
               proxy_http_version 1.1;
               proxy_set_header Upgrade $http_upgrade;
               proxy_set_header Connection 'upgrade';
               proxy_set_header Host $host;
               proxy_cache_bypass $http_upgrade;
        }

    location /chat {
                proxy_pass http://127.0.0.1:4555;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
        }
}

It was working when I was redirectioning the connection directly to the instance but now that we have the loadbalancer in the front it doesn’t work anymore.

web application output:

WebSocket connection to ‘wss://www.domain.com/socket.io/?EIO=3&transport=websocket’ failed: Error during WebSocket handshake: Unexpected response code: 200

And this is the headers:

Request URL: wss://www.domain.com/socket.io/?EIO=3&transport=websocket
Request Method: GET
Status Code: 200 OK
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection: keep-alive
Content-Type: text/html; charset=UTF-8
Date: Mon, 20 May 2019 18:53:37 GMT
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Pragma: no-cache
Server: nginx/1.14.1
Transfer-Encoding: chunked
X-Powered-By: PHP/5.6.40
Accept-Encoding: gzip, deflate, br
Accept-Language: pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7
Cache-Control: no-cache
Connection: Upgrade
Cookie: PHPSESSID=a6v5ebp25cajb1dj9s6je605a3
Host: www.domain.com
Origin: https://www. domain.com
Pragma: no-cache
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Sec-WebSocket-Key: kmYaufsBu3UFD+qGm1vlGA==
Sec-WebSocket-Version: 13
Upgrade: websocket
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36
EIO: 3
transport: websocket

I am trying to run a simple chat application from this tutorial: http://www.binarytides.com/websockets-php-tutorial/

I am using XAMPP localhost Apache with ports 80 and 443.

I keep getting: WebSocket connection to ‘ws://localhost/IceEscape/server.php/websocket’ failed: Error during WebSocket handshake: Unexpected response code: 200

What do I change to resolve this?

I have tried toying with the

var host = "ws://localhost:80/IceEscape/server.php/websocket";

also tried

var host = "ws://localhost:80/IceEscape/server.php";

code:

users.php:

<?php
class WebSocketUser {
  public $socket;
  public $id;
  public $headers = array();
  public $handshake = false;
  public $handlingPartialPacket = false;
  public $partialBuffer = "";
  public $sendingContinuous = false;
  public $partialMessage = "";

  public $hasSentClose = false;
  function __construct($id, $socket) {
    $this->id = $id;
    $this->socket = $socket;
  }
}

websockets.php:

<?php
//require_once('./daemonize.php');
require_once('./users.php');
abstract class WebSocketServer {
  protected $userClass = 'WebSocketUser'; // redefine this if you want a custom user class.  The custom user class should inherit from WebSocketUser.
  protected $maxBufferSize;        
  protected $master;
  protected $sockets                              = array();
  protected $users                                = array();
  protected $heldMessages                         = array();
  protected $interactive                          = true;
  protected $headerOriginRequired                 = false;
  protected $headerSecWebSocketProtocolRequired   = false;
  protected $headerSecWebSocketExtensionsRequired = false;
  function __construct($addr, $port, $bufferLength = 2048) {
    $this->maxBufferSize = $bufferLength;
    $this->master = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)  or die("Failed: socket_create()");
    socket_set_option($this->master, SOL_SOCKET, SO_REUSEADDR, 1) or die("Failed: socket_option()");
    socket_bind($this->master, $addr, $port)                      or die("Failed: socket_bind()");
    socket_listen($this->master,20)                               or die("Failed: socket_listen()");
    $this->sockets['m'] = $this->master;
    $this->stdout("Server startednListening on: $addr:$portnMaster socket: ".$this->master);

  }
  abstract protected function process($user,$message); // Called immediately when the data is recieved. 
  abstract protected function connected($user);        // Called after the handshake response is sent to the client.
  abstract protected function closed($user);           // Called after the connection is closed.
  protected function connecting($user) {
    // Override to handle a connecting user, after the instance of the User is created, but before
    // the handshake has completed.
  }

  protected function send($user, $message) {
    if ($user->handshake) {
      $message = $this->frame($message,$user);
      $result = @socket_write($user->socket, $message, strlen($message));
    }
    else {
      // User has not yet performed their handshake.  Store for sending later.
      $holdingMessage = array('user' => $user, 'message' => $message);
      $this->heldMessages[] = $holdingMessage;
    }
  }
  protected function tick() {
    // Override this for any process that should happen periodically.  Will happen at least once
    // per second, but possibly more often.
  }
  protected function _tick() {
    // Core maintenance processes, such as retrying failed messages.
    foreach ($this->heldMessages as $key => $hm) {
      $found = false;
      foreach ($this->users as $currentUser) {
        if ($hm['user']->socket == $currentUser->socket) {
          $found = true;
          if ($currentUser->handshake) {
            unset($this->heldMessages[$key]);
            $this->send($currentUser, $hm['message']);
          }
        }
      }
      if (!$found) {
        // If they're no longer in the list of connected users, drop the message.
        unset($this->heldMessages[$key]);
      }
    }
  }
  /**
   * Main processing loop
   */
  public function run() {
    while(true) {
      if (empty($this->sockets)) {
        $this->sockets['m'] = $this->master;
      }
      $read = $this->sockets;
      $write = $except = null;
      $this->_tick();
      $this->tick();
      @socket_select($read,$write,$except,1);
      foreach ($read as $socket) {
        if ($socket == $this->master) {
          $client = socket_accept($socket);
          if ($client < 0) {
            $this->stderr("Failed: socket_accept()");
            continue;
          } 
          else {
            $this->connect($client);
            $this->stdout("Client connected. " . $client);
          }
        } 
        else {
          $numBytes = @socket_recv($socket, $buffer, $this->maxBufferSize, 0); 
          if ($numBytes === false) {
            $sockErrNo = socket_last_error($socket);
            switch ($sockErrNo)
            {
              case 102: // ENETRESET    -- Network dropped connection because of reset
              case 103: // ECONNABORTED -- Software caused connection abort
              case 104: // ECONNRESET   -- Connection reset by peer
              case 108: // ESHUTDOWN    -- Cannot send after transport endpoint shutdown -- probably more of an error on our part, if we're trying to write after the socket is closed.  Probably not a critical error, though.
              case 110: // ETIMEDOUT    -- Connection timed out
              case 111: // ECONNREFUSED -- Connection refused -- We shouldn't see this one, since we're listening... Still not a critical error.
              case 112: // EHOSTDOWN    -- Host is down -- Again, we shouldn't see this, and again, not critical because it's just one connection and we still want to listen to/for others.
              case 113: // EHOSTUNREACH -- No route to host
              case 121: // EREMOTEIO    -- Rempte I/O error -- Their hard drive just blew up.
              case 125: // ECANCELED    -- Operation canceled

                $this->stderr("Unusual disconnect on socket " . $socket);
                $this->disconnect($socket, true, $sockErrNo); // disconnect before clearing error, in case someone with their own implementation wants to check for error conditions on the socket.
                break;
              default:
                $this->stderr('Socket error: ' . socket_strerror($sockErrNo));
            }

          }
          elseif ($numBytes == 0) {
            $this->disconnect($socket);
            $this->stderr("Client disconnected. TCP connection lost: " . $socket);
          } 
          else {
            $user = $this->getUserBySocket($socket);
            if (!$user->handshake) {
              $tmp = str_replace("r", '', $buffer);
              if (strpos($tmp, "nn") === false ) {
                continue; // If the client has not finished sending the header, then wait before sending our upgrade response.
              }
              $this->doHandshake($user,$buffer);
            } 
            else {
              //split packet into frame and send it to deframe
              $this->split_packet($numBytes,$buffer, $user);
            }
          }
        }
      }
    }
  }
  protected function connect($socket) {
    $user = new $this->userClass(uniqid('u'), $socket);
    $this->users[$user->id] = $user;
    $this->sockets[$user->id] = $socket;
    $this->connecting($user);
  }
  protected function disconnect($socket, $triggerClosed = true, $sockErrNo = null) {
    $disconnectedUser = $this->getUserBySocket($socket);

    if ($disconnectedUser !== null) {
      unset($this->users[$disconnectedUser->id]);

      if (array_key_exists($disconnectedUser->id, $this->sockets)) {
        unset($this->sockets[$disconnectedUser->id]);
      }

      if (!is_null($sockErrNo)) {
        socket_clear_error($socket);
      }
      if ($triggerClosed) {
        $this->closed($disconnectedUser);
        socket_close($disconnectedUser->socket);
      }
      else {
        $message = $this->frame('', $disconnectedUser, 'close');
        @socket_write($disconnectedUser->socket, $message, strlen($message));
      }
    }
  }
  protected function doHandshake($user, $buffer) {
    $magicGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
    $headers = array();
    $lines = explode("n",$buffer);
    foreach ($lines as $line) {
      if (strpos($line,":") !== false) {
        $header = explode(":",$line,2);
        $headers[strtolower(trim($header[0]))] = trim($header[1]);
      }
      elseif (stripos($line,"get ") !== false) {
        preg_match("/GET (.*) HTTP/i", $buffer, $reqResource);
        $headers['get'] = trim($reqResource[1]);
      }
    }
    if (isset($headers['get'])) {
      $user->requestedResource = $headers['get'];
    } 
    else {
      // todo: fail the connection
      $handshakeResponse = "HTTP/1.1 405 Method Not Allowedrnrn";     
    }
    if (!isset($headers['host']) || !$this->checkHost($headers['host'])) {
      $handshakeResponse = "HTTP/1.1 400 Bad Request";
    }
    if (!isset($headers['upgrade']) || strtolower($headers['upgrade']) != 'websocket') {
      $handshakeResponse = "HTTP/1.1 400 Bad Request";
    } 
    if (!isset($headers['connection']) || strpos(strtolower($headers['connection']), 'upgrade') === FALSE) {
      $handshakeResponse = "HTTP/1.1 400 Bad Request";
    }
    if (!isset($headers['sec-websocket-key'])) {
      $handshakeResponse = "HTTP/1.1 400 Bad Request";
    } 
    else {
    }
    if (!isset($headers['sec-websocket-version']) || strtolower($headers['sec-websocket-version']) != 13) {
      $handshakeResponse = "HTTP/1.1 426 Upgrade RequiredrnSec-WebSocketVersion: 13";
    }
    if (($this->headerOriginRequired && !isset($headers['origin']) ) || ($this->headerOriginRequired && !$this->checkOrigin($headers['origin']))) {
      $handshakeResponse = "HTTP/1.1 403 Forbidden";
    }
    if (($this->headerSecWebSocketProtocolRequired && !isset($headers['sec-websocket-protocol'])) || ($this->headerSecWebSocketProtocolRequired && !$this->checkWebsocProtocol($headers['sec-websocket-protocol']))) {
      $handshakeResponse = "HTTP/1.1 400 Bad Request";
    }
    if (($this->headerSecWebSocketExtensionsRequired && !isset($headers['sec-websocket-extensions'])) || ($this->headerSecWebSocketExtensionsRequired && !$this->checkWebsocExtensions($headers['sec-websocket-extensions']))) {
      $handshakeResponse = "HTTP/1.1 400 Bad Request";
    }
    // Done verifying the _required_ headers and optionally required headers.
    if (isset($handshakeResponse)) {
      socket_write($user->socket,$handshakeResponse,strlen($handshakeResponse));
      $this->disconnect($user->socket);
      return;
    }
    $user->headers = $headers;
    $user->handshake = $buffer;
    $webSocketKeyHash = sha1($headers['sec-websocket-key'] . $magicGUID);
    $rawToken = "";
    for ($i = 0; $i < 20; $i++) {
      $rawToken .= chr(hexdec(substr($webSocketKeyHash,$i*2, 2)));
    }
    $handshakeToken = base64_encode($rawToken) . "rn";
    $subProtocol = (isset($headers['sec-websocket-protocol'])) ? $this->processProtocol($headers['sec-websocket-protocol']) : "";
    $extensions = (isset($headers['sec-websocket-extensions'])) ? $this->processExtensions($headers['sec-websocket-extensions']) : "";
    $handshakeResponse = "HTTP/1.1 101 Switching ProtocolsrnUpgrade: websocketrnConnection: UpgradernSec-WebSocket-Accept: $handshakeToken$subProtocol$extensionsrn";
    socket_write($user->socket,$handshakeResponse,strlen($handshakeResponse));
    $this->connected($user);
  }
  protected function checkHost($hostName) {
    return true; // Override and return false if the host is not one that you would expect.
                 // Ex: You only want to accept hosts from the my-domain.com domain,
                 // but you receive a host from malicious-site.com instead.
  }
  protected function checkOrigin($origin) {
    return true; // Override and return false if the origin is not one that you would expect.
  }
  protected function checkWebsocProtocol($protocol) {
    return true; // Override and return false if a protocol is not found that you would expect.
  }
  protected function checkWebsocExtensions($extensions) {
    return true; // Override and return false if an extension is not found that you would expect.
  }
  protected function processProtocol($protocol) {
    return ""; // return either "Sec-WebSocket-Protocol: SelectedProtocolFromClientListrn" or return an empty string.  
           // The carriage return/newline combo must appear at the end of a non-empty string, and must not
           // appear at the beginning of the string nor in an otherwise empty string, or it will be considered part of 
           // the response body, which will trigger an error in the client as it will not be formatted correctly.
  }
  protected function processExtensions($extensions) {
    return ""; // return either "Sec-WebSocket-Extensions: SelectedExtensionsrn" or return an empty string.
  }
  protected function getUserBySocket($socket) {
    foreach ($this->users as $user) {
      if ($user->socket == $socket) {
        return $user;
      }
    }
    return null;
  }
  public function stdout($message) {
    if ($this->interactive) {
      echo "$messagen";
    }
  }
  public function stderr($message) {
    if ($this->interactive) {
      echo "$messagen";
    }
  }
  protected function frame($message, $user, $messageType='text', $messageContinues=false) {
    switch ($messageType) {
      case 'continuous':
        $b1 = 0;
        break;
      case 'text':
        $b1 = ($user->sendingContinuous) ? 0 : 1;
        break;
      case 'binary':
        $b1 = ($user->sendingContinuous) ? 0 : 2;
        break;
      case 'close':
        $b1 = 8;
        break;
      case 'ping':
        $b1 = 9;
        break;
      case 'pong':
        $b1 = 10;
        break;
    }
    if ($messageContinues) {
      $user->sendingContinuous = true;
    } 
    else {
      $b1 += 128;
      $user->sendingContinuous = false;
    }
    $length = strlen($message);
    $lengthField = "";
    if ($length < 126) {
      $b2 = $length;
    } 
    elseif ($length <= 65536) {
      $b2 = 126;
      $hexLength = dechex($length);
      //$this->stdout("Hex Length: $hexLength");
      if (strlen($hexLength)%2 == 1) {
        $hexLength = '0' . $hexLength;
      } 
      $n = strlen($hexLength) - 2;
      for ($i = $n; $i >= 0; $i=$i-2) {
        $lengthField = chr(hexdec(substr($hexLength, $i, 2))) . $lengthField;
      }
      while (strlen($lengthField) < 2) {
        $lengthField = chr(0) . $lengthField;
      }
    } 
    else {
      $b2 = 127;
      $hexLength = dechex($length);
      if (strlen($hexLength)%2 == 1) {
        $hexLength = '0' . $hexLength;
      } 
      $n = strlen($hexLength) - 2;
      for ($i = $n; $i >= 0; $i=$i-2) {
        $lengthField = chr(hexdec(substr($hexLength, $i, 2))) . $lengthField;
      }
      while (strlen($lengthField) < 8) {
        $lengthField = chr(0) . $lengthField;
      }
    }
    return chr($b1) . chr($b2) . $lengthField . $message;
  }

  //check packet if he have more than one frame and process each frame individually
  protected function split_packet($length,$packet, $user) {
    //add PartialPacket and calculate the new $length
    if ($user->handlingPartialPacket) {
      $packet = $user->partialBuffer . $packet;
      $user->handlingPartialPacket = false;
      $length=strlen($packet);
    }
    $fullpacket=$packet;
    $frame_pos=0;
    $frame_id=1;
    while($frame_pos<$length) {
      $headers = $this->extractHeaders($packet);
      $headers_size = $this->calcoffset($headers);
      $framesize=$headers['length']+$headers_size;

      //split frame from packet and process it
      $frame=substr($fullpacket,$frame_pos,$framesize);
      if (($message = $this->deframe($frame, $user,$headers)) !== FALSE) {
        if ($user->hasSentClose) {
          $this->disconnect($user->socket);
        } else {
          if ((preg_match('//u', $message)) || ($headers['opcode']==2)) {
            //$this->stdout("Text msg encoded UTF-8 or Binary msgn".$message); 
            $this->process($user, $message);
          } else {
            $this->stderr("not UTF-8n");
          }
        }
      } 
      //get the new position also modify packet data
      $frame_pos+=$framesize;
      $packet=substr($fullpacket,$frame_pos);
      $frame_id++;
    }
  }
  protected function calcoffset($headers) {
    $offset = 2;
    if ($headers['hasmask']) {
      $offset += 4;
    }
    if ($headers['length'] > 65535) {
      $offset += 8;
    } elseif ($headers['length'] > 125) {
      $offset += 2;
    }
    return $offset;
  }
  protected function deframe($message, &$user) {
    //echo $this->strtohex($message);
    $headers = $this->extractHeaders($message);
    $pongReply = false;
    $willClose = false;
    switch($headers['opcode']) {
      case 0:
      case 1:
      case 2:
        break;
      case 8:
        // todo: close the connection
        $user->hasSentClose = true;
        return "";
      case 9:
        $pongReply = true;
      case 10:
        break;
      default:
        //$this->disconnect($user); // todo: fail connection
        $willClose = true;
        break;
    }
    /* Deal by split_packet() as now deframe() do only one frame at a time.
    if ($user->handlingPartialPacket) {
      $message = $user->partialBuffer . $message;
      $user->handlingPartialPacket = false;
      return $this->deframe($message, $user);
    }
    */

    if ($this->checkRSVBits($headers,$user)) {
      return false;
    }
    if ($willClose) {
      // todo: fail the connection
      return false;
    }
    $payload = $user->partialMessage . $this->extractPayload($message,$headers);
    if ($pongReply) {
      $reply = $this->frame($payload,$user,'pong');
      socket_write($user->socket,$reply,strlen($reply));
      return false;
    }
    if ($headers['length'] > strlen($this->applyMask($headers,$payload))) {
        $user->handlingPartialPacket = true;
        $user->partialBuffer = $message;
        return false;
    }
    $payload = $this->applyMask($headers,$payload);
    if ($headers['fin']) {
      $user->partialMessage = "";
      return $payload;
    }
    $user->partialMessage = $payload;
    return false;
  }
  protected function extractHeaders($message) {
    $header = array('fin'     => $message[0] & chr(128),
            'rsv1'    => $message[0] & chr(64),
            'rsv2'    => $message[0] & chr(32),
            'rsv3'    => $message[0] & chr(16),
            'opcode'  => ord($message[0]) & 15,
            'hasmask' => $message[1] & chr(128),
            'length'  => 0,
            'mask'    => "");
    $header['length'] = (ord($message[1]) >= 128) ? ord($message[1]) - 128 : ord($message[1]);
    if ($header['length'] == 126) {
      if ($header['hasmask']) {
        $header['mask'] = $message[4] . $message[5] . $message[6] . $message[7];
      }
      $header['length'] = ord($message[2]) * 256 
                + ord($message[3]);
    } 
    elseif ($header['length'] == 127) {
      if ($header['hasmask']) {
        $header['mask'] = $message[10] . $message[11] . $message[12] . $message[13];
      }
      $header['length'] = ord($message[2]) * 65536 * 65536 * 65536 * 256 
                + ord($message[3]) * 65536 * 65536 * 65536
                + ord($message[4]) * 65536 * 65536 * 256
                + ord($message[5]) * 65536 * 65536
                + ord($message[6]) * 65536 * 256
                + ord($message[7]) * 65536 
                + ord($message[8]) * 256
                + ord($message[9]);
    } 
    elseif ($header['hasmask']) {
      $header['mask'] = $message[2] . $message[3] . $message[4] . $message[5];
    }
    //echo $this->strtohex($message);
    //$this->printHeaders($header);
    return $header;
  }
  protected function extractPayload($message,$headers) {
    $offset = 2;
    if ($headers['hasmask']) {
      $offset += 4;
    }
    if ($headers['length'] > 65535) {
      $offset += 8;
    } 
    elseif ($headers['length'] > 125) {
      $offset += 2;
    }
    return substr($message,$offset);
  }
  protected function applyMask($headers,$payload) {
    $effectiveMask = "";
    if ($headers['hasmask']) {
      $mask = $headers['mask'];
    } 
    else {
      return $payload;
    }
    while (strlen($effectiveMask) < strlen($payload)) {
      $effectiveMask .= $mask;
    }
    while (strlen($effectiveMask) > strlen($payload)) {
      $effectiveMask = substr($effectiveMask,0,-1);
    }
    return $effectiveMask ^ $payload;
  }
  protected function checkRSVBits($headers,$user) { // override this method if you are using an extension where the RSV bits are used.
    if (ord($headers['rsv1']) + ord($headers['rsv2']) + ord($headers['rsv3']) > 0) {
      //$this->disconnect($user); // todo: fail connection
      return true;
    }
    return false;
  }
  protected function strtohex($str) {
    $strout = "";
    for ($i = 0; $i < strlen($str); $i++) {
      $strout .= (ord($str[$i])<16) ? "0" . dechex(ord($str[$i])) : dechex(ord($str[$i]));
      $strout .= " ";
      if ($i%32 == 7) {
        $strout .= ": ";
      }
      if ($i%32 == 15) {
        $strout .= ": ";
      }
      if ($i%32 == 23) {
        $strout .= ": ";
      }
      if ($i%32 == 31) {
        $strout .= "n";
      }
    }
    return $strout . "n";
  }
  protected function printHeaders($headers) {
    echo "Arrayn(n";
    foreach ($headers as $key => $value) {
      if ($key == 'length' || $key == 'opcode') {
        echo "t[$key] => $valuenn";
      } 
      else {
        echo "t[$key] => ".$this->strtohex($value)."n";
      }
    }
    echo ")n";
  }

server.php:

<?php

require_once('websockets.php');

class echo_server extends WebSocketServer 
{
    //protected $maxBufferSize = 1048576; //1MB... overkill for an echo server, but potentially plausible for other applications.

    protected function process ($user, $message) 
    {
        if($message == 'help')
        {
            $reply = 'Following commands are available - date, hi';
        }
        else if($message == 'date')
        {
            $reply = "Current date is " . date('Y-m-d H:i:s');
        }
        else if($message == 'hi')
        {
            $reply = "Hello user. This is a websocket server.";
        }
        else
        {
            $reply = "Thank you for the message : $message";
        }

        $this->send($user, $reply);

        //The uri component say /a/b/c
        echo "Requested resource : " . $user->requestedResource . "n";
    }

    /**
        This is run when socket connection is established. Send a greeting message
    */
    protected function connected ($user) 
    {
        //Send welcome message to user
        $welcome_message = 'Hello. Welcome to the Websocket server. Type help to see what commands are available.';
        $this->send($user, $welcome_message);
    }

    /**
        This is where cleanup would go, in case the user had any sort of
        open files or other objects associated with them.  This runs after the socket 
        has been closed, so there is no need to clean up the socket itself here.
    */
    protected function closed ($user) 
    {
        echo "User closed connectionn";
    }
}

$host = '127.0.0.1';
$port = 80;

$server = new echo_server($host , $port );

client.html:

<html><head><title>WebSocket</title>
<style type="text/css">
html,body {
    font:normal 0.9em arial,helvetica;
}
#log {
    width:600px; 
    height:300px; 
    border:1px solid #7F9DB9; 
    overflow:auto;
}
#msg {
    width:400px;
}
</style>
<script type="text/javascript">
var socket;
function init() {
    var host = "ws://localhost:80/IceEscape/server.php/websocket"; // SET THIS TO YOUR SERVER
    try {
        socket = new WebSocket(host);
        log('WebSocket - status '+socket.readyState);
        socket.onopen    = function(msg) { 
                               log("Welcome - status "+this.readyState); 
                           };
        socket.onmessage = function(msg) { 
                               log("Received: "+msg.data); 
                           };
        socket.onclose   = function(msg) { 
                               log("Disconnected - status "+this.readyState); 
                           };
    }
    catch(ex){ 
        log(ex); 
    }
    $("msg").focus();
}
function send(){
    var txt,msg;
    txt = $("msg");
    msg = txt.value;
    if(!msg) { 
        alert("Message can not be empty"); 
        return; 
    }
    txt.value="";
    txt.focus();
    try { 
        socket.send(msg); 
        log('Sent: '+msg); 
    } catch(ex) { 
        log(ex); 
    }
}
function quit(){
    if (socket != null) {
        log("Goodbye!");
        socket.close();
        socket=null;
    }
}
function reconnect() {
    quit();
    init();
}
// Utilities
function $(id){ return document.getElementById(id); }
function log(msg){ $("log").innerHTML+="<br>"+msg; }
function onkey(event){ if(event.keyCode==13){ send(); } }
</script>

</head>
<body onload="init()">
<h3>WebSocket v2.00</h3>
<div id="log"></div>
<input id="msg" type="textbox" onkeypress="onkey(event)"/>
<button onclick="send()">Send</button>
<button onclick="quit()">Quit</button>
<button onclick="reconnect()">Reconnect</button>
</body>
</html>

So I am trying to set up a website that also has websockets where both the http-server and the websocket listens on the same port:

const WebSocket = require('ws');
var express = require('express');
var app = express();

wss = new WebSocket.Server({server : app});

app.get('/', function(req, res){

res.send('hello world!');
});

wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});

ws.send('some text');
});

app.listen(8080, function(){

console.log('app started');
});

If I then load the servers website in chrome-browser I am greeted with «hello world!». So far so good. But if I open up the webconsole and try to connect with

var exampleSocket = new WebSocket("ws://192.10.10.30:8080");

I get the following errormessage:

WebSocket connection to ‘ws://192.10.10.30:8080/’ failed: Error
during WebSocket handshake: Unexpected response code: 200

My first thought was, do I have to explicitly declare an http-server ?

But I read this post
Serve WebSocket and HTTP server at same address on Node.js and there was no http-server explicitly declared. Please help me on this.

javascript node.js express websocket

asked Nov 26 ’18 at 16:54

So I am trying to set up a website that also has websockets where both the http-server and the websocket listens on the same port:

const WebSocket = require('ws');
var express = require('express');
var app = express();

wss = new WebSocket.Server({server : app});

app.get('/', function(req, res){

res.send('hello world!');
});

wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});

ws.send('some text');
});

app.listen(8080, function(){

console.log('app started');
});

If I then load the servers website in chrome-browser I am greeted with «hello world!». So far so good. But if I open up the webconsole and try to connect with

var exampleSocket = new WebSocket("ws://192.10.10.30:8080");

I get the following errormessage:

WebSocket connection to ‘ws://192.10.10.30:8080/’ failed: Error
during WebSocket handshake: Unexpected response code: 200

My first thought was, do I have to explicitly declare an http-server ?

But I read this post
Serve WebSocket and HTTP server at same address on Node.js and there was no http-server explicitly declared. Please help me on this.

javascript node.js express websocket

asked Nov 26 ’18 at 16:54

1

So I am trying to set up a website that also has websockets where both the http-server and the websocket listens on the same port:

const WebSocket = require('ws');
var express = require('express');
var app = express();

wss = new WebSocket.Server({server : app});

app.get('/', function(req, res){

res.send('hello world!');
});

wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});

ws.send('some text');
});

app.listen(8080, function(){

console.log('app started');
});

If I then load the servers website in chrome-browser I am greeted with «hello world!». So far so good. But if I open up the webconsole and try to connect with

var exampleSocket = new WebSocket("ws://192.10.10.30:8080");

I get the following errormessage:

WebSocket connection to ‘ws://192.10.10.30:8080/’ failed: Error
during WebSocket handshake: Unexpected response code: 200

My first thought was, do I have to explicitly declare an http-server ?

But I read this post
Serve WebSocket and HTTP server at same address on Node.js and there was no http-server explicitly declared. Please help me on this.

javascript node.js express websocket

asked Nov 26 ’18 at 16:54

So I am trying to set up a website that also has websockets where both the http-server and the websocket listens on the same port:

const WebSocket = require('ws');
var express = require('express');
var app = express();

wss = new WebSocket.Server({server : app});

app.get('/', function(req, res){

res.send('hello world!');
});

wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});

ws.send('some text');
});

app.listen(8080, function(){

console.log('app started');
});

If I then load the servers website in chrome-browser I am greeted with «hello world!». So far so good. But if I open up the webconsole and try to connect with

var exampleSocket = new WebSocket("ws://192.10.10.30:8080");

I get the following errormessage:

WebSocket connection to ‘ws://192.10.10.30:8080/’ failed: Error
during WebSocket handshake: Unexpected response code: 200

My first thought was, do I have to explicitly declare an http-server ?

But I read this post
Serve WebSocket and HTTP server at same address on Node.js and there was no http-server explicitly declared. Please help me on this.

javascript node.js express websocket

javascript node.js express websocket

asked Nov 26 ’18 at 16:54

asked Nov 26 ’18 at 16:54

asked Nov 26 ’18 at 16:54

asked Nov 26 ’18 at 16:54

asked Nov 26 ’18 at 16:54

You’re passing an Express app instance as server, which should be an HTTP/HTTPS server instance. Such an instance is returned by app.listen:

var app = express();
var server = app.listen(8080, function(){
console.log('app started');
});

wss = new WebSocket.Server({server : server});

answered Nov 26 ’18 at 20:03

Your Answer

StackExchange.ifUsing(«editor», function () {
StackExchange.using(«externalEditor», function () {
StackExchange.using(«snippets», function () {
StackExchange.snippets.init();
});
});
}, «code-snippets»);

StackExchange.ready(function() {
var channelOptions = {
tags: «».split(» «),
id: «1»
};
initTagRenderer(«».split(» «), «».split(» «), channelOptions);

StackExchange.using(«externalEditor», function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using(«snippets», function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: ‘answer’,
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: «»,
imageUploader: {
brandingHtml: «Powered by u003ca class=»icon-imgur-white» href=»https://imgur.com/»u003eu003c/au003e»,
contentPolicyHtml: «User contributions licensed under u003ca href=»https://creativecommons.org/licenses/by-sa/3.0/»u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href=»https://stackoverflow.com/legal/content-policy»u003e(content policy)u003c/au003e»,
allowUrls: true
},
onDemand: true,
discardSelector: «.discard-answer»
,immediatelyShowMarkdownHelp:true
});

}
});

Sign up or log in

StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave(‘#login-link’);
});

Sign up using Email and Password

Post as a guest

Email

Required, but never shown

StackExchange.ready(
function () {
StackExchange.openid.initPostLogin(‘.new-post-login’, ‘https%3a%2f%2fstackoverflow.com%2fquestions%2f53485713%2fnode-js-with-express-and-websocket-giving-error-during-websocket-handshake-unex%23new-answer’, ‘question_page’);
}
);

Post as a guest

Email

Required, but never shown

You’re passing an Express app instance as server, which should be an HTTP/HTTPS server instance. Such an instance is returned by app.listen:

var app = express();
var server = app.listen(8080, function(){
console.log('app started');
});

wss = new WebSocket.Server({server : server});

answered Nov 26 ’18 at 20:03

You’re passing an Express app instance as server, which should be an HTTP/HTTPS server instance. Such an instance is returned by app.listen:

var app = express();
var server = app.listen(8080, function(){
console.log('app started');
});

wss = new WebSocket.Server({server : server});

answered Nov 26 ’18 at 20:03

0

You’re passing an Express app instance as server, which should be an HTTP/HTTPS server instance. Such an instance is returned by app.listen:

var app = express();
var server = app.listen(8080, function(){
console.log('app started');
});

wss = new WebSocket.Server({server : server});

answered Nov 26 ’18 at 20:03

You’re passing an Express app instance as server, which should be an HTTP/HTTPS server instance. Such an instance is returned by app.listen:

var app = express();
var server = app.listen(8080, function(){
console.log('app started');
});

wss = new WebSocket.Server({server : server});

answered Nov 26 ’18 at 20:03

answered Nov 26 ’18 at 20:03

answered Nov 26 ’18 at 20:03

answered Nov 26 ’18 at 20:03

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.

Sign up or log in

StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave(‘#login-link’);
});

Sign up using Email and Password

Post as a guest

Email

Required, but never shown

StackExchange.ready(
function () {
StackExchange.openid.initPostLogin(‘.new-post-login’, ‘https%3a%2f%2fstackoverflow.com%2fquestions%2f53485713%2fnode-js-with-express-and-websocket-giving-error-during-websocket-handshake-unex%23new-answer’, ‘question_page’);
}
);

Post as a guest

Email

Required, but never shown

Sign up or log in

StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave(‘#login-link’);
});

Sign up using Email and Password

Post as a guest

Email

Required, but never shown

Sign up or log in

StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave(‘#login-link’);
});

Sign up using Email and Password

Post as a guest

Email

Required, but never shown

Sign up or log in

StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave(‘#login-link’);
});

Sign up using Email and Password

Sign up using Email and Password

Post as a guest

Email

Required, but never shown

Email

Required, but never shown

Email

Required, but never shown

Email

Required, but never shown

Email

Required, but never shown

Email

Required, but never shown

Email

Required, but never shown

Email

Required, but never shown

Email

Required, but never shown

Понравилась статья? Поделить с друзьями:
  • Failed error 0xc004f074 при активации kmsauto
  • Failed error 0xc004f074 kmsauto windows 10
  • Failed error 0xc004f074 kms активатор office
  • Failed error 0xc004f035 при активации kmsauto
  • Failed error 0xc004e015