dersar00

dersar00

Hello, when I try to connect to my local websocket server I got error, but when I connect to wss://echo.websocket.org everything is good. If I try to connect to server through simply js client everything works nice too.

Websocket server:

require 'socket'
require 'digest/sha1'

server = TCPServer.new('localhost', 2345)

loop do

  socket = server.accept
  STDERR.puts "Incoming Request"

  http_request = ""
  while (line = socket.gets) && (line != "\r\n")
    http_request += line
  end

  if matches = http_request.match(/^Sec-WebSocket-Key: (\S+)/)
    websocket_key = matches[1]
    STDERR.puts "Websocket handshake detected with key: #{ websocket_key }"
  else
    STDERR.puts "Aborting non-websocket connection"
    socket.close
    next
  end


  response_key = Digest::SHA1.base64digest([websocket_key, "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"].join)
  STDERR.puts "Responding to handshake with key: #{ response_key }"

  socket.write <<-eos
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: #{ response_key }

  eos

  STDERR.puts "Handshake completed. Starting to parse the websocket frame."

  first_byte = socket.getbyte
  fin = first_byte & 0b10000000
  opcode = first_byte & 0b00001111

  raise "We don't support continuations" unless fin
  raise "We only support opcode 1" unless opcode == 1

  second_byte = socket.getbyte
  is_masked = second_byte & 0b10000000
  payload_size = second_byte & 0b01111111

  raise "All incoming frames should be masked according to the websocket spec" unless is_masked
  raise "We only support payloads < 126 bytes in length" unless payload_size < 126

  STDERR.puts "Payload size: #{ payload_size } bytes"

  mask = 4.times.map { socket.getbyte }
  STDERR.puts "Got mask: #{ mask.inspect }"

  data = payload_size.times.map { socket.getbyte }
  STDERR.puts "Got masked data: #{ data.inspect }"

  unmasked_data = data.each_with_index.map { |byte, i| byte ^ mask[i % 4] }
  STDERR.puts "Unmasked the data: #{ unmasked_data.inspect }"

  STDERR.puts "Converted to a string: #{ unmasked_data.pack('C*').force_encoding('utf-8').inspect }"

  socket.close
end

Websockex worker:

defmodule DispatcherService.Websockets do
  use WebSockex
  require Logger

  def start_link(state \\ []) do
    WebSockex.start_link("wss://echo.websocket.org", __MODULE__, state)
  end

  def handle_connect(_conn, state) do
     Logger.info("Binance Client Connected!")
     {:ok, state}
   end

  def handle_disconnect(%{reason: reason}, state) do
    Logger.warn "websocket closing: #{inspect reason}"
    {:ok, state}
  end

  def handle_frame({:binary, frame}, state) do
    IO.inspect "Received frame"
    {:ok, state}
  end
end

Btw, my js client:

<!doctype html>
<html lang="en">
<head>
  <title>Websocket Client</title>
</head>
<body>
  <script>
    var exampleSocket = new WebSocket("ws://localhost:2345");
    exampleSocket.onopen = function (event) {
      exampleSocket.send("Can you hear me?"); 
    };
    exampleSocket.onmessage = function (event) {
      console.log(event.data);
    }
  </script>
</body>
</html>

Showing Posts 1 to 5

dersar00

dersar00 OP

@Azolo, I think I need u’r help.

Ankhers

Ankhers

Can you show the error that you are getting?

dersar00

dersar00 OP

16:58:37.947 [error] Supervisor 'Elixir.DispatcherService.Supervisor' had child 'Elixir.DispatcherService.Websockets' started with 'Elixir.DispatcherService.Websockets':start_link(<<"ws://localhost:2345">>) at undefined exit with reason #{'__exception__' => true,'__struct__' => 'Elixir.WebSockex.ConnError',original => timeout} in context start_error
16:58:37.947 [error] CRASH REPORT Process <0.260.0> with 0 neighbours exited with reason: {{shutdown,{failed_to_start_child,'Elixir.DispatcherService.Websockets',#{'__exception__' => true,'__struct__' => 'Elixir.WebSockex.ConnError',original => timeout}}},{'Elixir.DispatcherService.Application',start,[normal,[]]}} in application_master:init/4 line 134

16:58:38.020 [info]  Application dispatcher_service exited: DispatcherService.Application.start(:normal, []) returned an error: shutdown: failed to start child: DispatcherService.Websockets
    ** (EXIT) %WebSockex.ConnError{original: :timeout}
16:58:38.020 [info] Application dispatcher_service exited with reason: {{shutdown,{failed_to_start_child,'Elixir.DispatcherService.Websockets',#{'__exception__' => true,'__struct__' => 'Elixir.WebSockex.ConnError',original => timeout}}},{'Elixir.DispatcherService.Application',start,[normal,[]]}}
** (Mix) Could not start application dispatcher_service: DispatcherService.Application.start(:normal, []) returned an error: shutdown: failed to start child: DispatcherService.Websockets
    ** (EXIT) %WebSockex.ConnError{original: :timeout}
Azolo

Azolo

Is that returning CRLFCRLF or just LFLF?

More than likely the browser conventions are more forgiving to the spec than WebSockex. But make sure those are returning carriage returns and line feeds.

Azolo

Azolo

@dersar00 Did that help you out or is there something else going on?

— All posts loaded —

Where Next? Top

Trending in Questions Top

Hellowman
Hello everyone! I am new to coding with Elixir/Erlang. And i am looking for some utilities for fuzzing testing like AFL++. Does anyone ...
New
yarrichar
I’m very new to Elixir, so sorry if this is a silly question: I am wondering what happens to the mailbox of a process when the machine i...
New
pragdave
How do I tell Hologram not to escape HTML when substituting into templates? {Textile.render(@product.long_description)} escapes the HTM...
New
Fl4m3Ph03n1x
Background When trying to execute mix release on a Windows 11 machine for a Phoenix project I get the following error: * assembling mark...
New
mandar1045
I load tested a plain Phoenix chat app backed by Postgres with 100 million messages in it, everything on default settings, to see what br...
New
rlipscombe
I’d like to create a file with 600 permissions (rw-------), but there’s a race condition if I create it and then change the permissions. ...
New
saleyn
Is there a way to import record definitions in the iex shell for pretty printing (similar to the rr command in the erl shell)? This woul...
New

Other Trending Topics Top

dominicletz
Hey there, I haven’t seen a list of useful Elixir specific skills for the popular AI tools yet so I’m starting one here with my first. ...
New
raa-ziq
Hi everyone :waving_hand: I wanted to share something I’ve been building — NowBlind, a random chat app designed to help people discover ...
New
mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
OndrejValenta
(I just needed to vent somewhere and LinkedIn is full of hope, or hype, I’m not sure which exactly) AI dream has many faces, but general...
New
kip
Localize is the next generation localisation library for Elixir. Think of it as ex_cldr version 3.0. The first version will be released ...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews