niv / websocket.nim

websockets for nim
http://niv.github.io/websocket.nim/docs/0.1.1/websocket.html
Other
101 stars 25 forks source link

help sendText async is recieved to html webview binary #69

Open AS400JPLPC opened 3 years ago

AS400JPLPC commented 3 years ago

hello, at the beginning I was very happy because while reading the code I found that the protocol was respected.

But when I used this with webview or the firefox browser the sendText sent by the server is binary I work in async

could you make it text, because the web protocol receives it like a blod, of course we can set up a gas factory to read but that loses its charm and makes conversations very complex

your example with await ws.sendText ("thanks for the data!") sends a binary received as a blod

thank you (excuse me for my english it's google)

Araq commented 3 years ago

Sorry, this is incomprehensible. What do you mean?

AS400JPLPC commented 3 years ago

your example with await ws.sendText ("thanks for the data!")from server
see your example

received browser html protocol websocket

    websocket.onmessage = function(event) {

        console.debug("WebSocket message received:", event.data);  ??? blod ->  undefine this description degug
        //I am forced to use the FileReader () function; to decrypt the object event.data for text 
        }


for there is something wrong I looked at your source code

code.text should not turn into alert(event.data) = {blod}

in your code we also see a simple sendText not async, it turns the function into binary

but I'm only using async so I'm using await ws.sendText ("Hello")


while the sendText async sends sendText with code.Text

and in the browser we receive a {Blod}


I was forced to give up and take WS to make the socket. Too bad because I found your solution very coherent. Unless you corrected it.

I controlled with mozilla the protocol and the way of receiving ... in "C" my server was working at work

there may be a difference with a correction, because explorer or firefox I tested that it has the same protocol

mratsim commented 3 years ago

Translation from the Discord: https://discord.com/channels/371759389889003530/725615956306690099/791555477049442314

With the following websocket message on Firefox:

await ws.sendText("Bonjour") 

he receives either undefine this description

websocket.onmessage = function(event) { 
  console.debug( event.data);  //  'undefine this description'
}

or {bold}

websocket.onmessage = function(event) { 
  alert(event.data);   // {bold}
}

On another webserver it works and so he suspects that there is an encoding issue

metagn commented 3 years ago

Very bizarre problem, I can't reproduce, it works fine for me, I also use Firefox (nightly 2020-10-02) but am on Windows. Server code:

import websocket, asynchttpserver, asyncnet, asyncdispatch

let server = newAsyncHttpServer()

proc cb(req: Request) {.async.} =
  let (ws, error) = await verifyWebsocketRequest(req)

  if ws.isNil:
    echo "WS negotiation failed: ", error
    await req.respond(Http400, "Websocket negotiation failed: " & $error)
    req.client.close()
    return

  echo "New websocket customer arrived!"
  while true:
    await sleepAsync(6000)
    await ws.sendText("hello")

waitFor server.serve(Port(8080), cb)

Page:

<script type="text/javascript">
let ws = new WebSocket("ws://localhost:8080")
ws.onmessage = function (event) {
    alert(event.data); // or console.log
}
</script>

I also understand it to be an encoding issue, perhaps we are sending an extra \0 somewhere?

AS400JPLPC commented 3 years ago

please I go up the code and I post it

AS400JPLPC commented 3 years ago

Linux firefox 84.01 Manajro last update

import websocket ,asynchttpserver,  asyncdispatch
import threadpool

import os

proc observer() {.thread} =

  #---------------------------------------------------------------------
  echo "start observer"
  let server = newAsyncHttpServer()

  proc cb(req: Request ; ) {.async.} =

    type
      FoncWork = object
        name: string
        arg: string
    let (ws, error) = await verifyWebsocketRequest(req, "myfancyprotocol")

    if ws.isNil:
      echo "WS negotiation failed: ", error
      await req.respond(Http400, "Websocket negotiation failed: " & $error)
      return

    echo "New websocket customer arrived!"
    while true:
      let (opcode, data) = await ws.readData()
      echo "(opcode: ", opcode, ", data length: ", data.len, ")"
      case opcode
      of Opcode.Text:
        echo data
        await ws.sendText("thanks for the data!")

      of Opcode.Binary:
        await ws.sendBinary(data)

      of Opcode.Close:
        let (closeCode, reason) = extractCloseData(data)
        echo "socket went away, close code: ", closeCode, ", reason: ", reason
        echo "Opcode.Close stop observer"
        # only exemple
        quit(QuitSuccess)

      else: discard
  waitFor server.serve(Port(9200),cb)
  quit(QuitSuccess)

spawnX(observer())
while true : discard

<!DOCTYPE html>
<html lang="fr-FR">
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">

    <script src="js/libs/jquery-3.1.0.js"></script>
    <link rel="stylesheet" href="css/JPLw3.css">

    </head>

<body class="w3-sand "  >

<h1>Input Form css w3schools </h1>

<form id="formid" >
  <fieldset>
<br>

<table>

    <tr>    <td><br></td>   </tr>
  <tr>
        <td>Nom</td>
        <td>
            <div class="w3-tooltip">
                <input type="text" maxlength="30" class="inputccs" id="NOM" style="width: 550px;">
                <span id='errNOM' style="position:absolute;left:0;bottom:+30px "    class="w3-text w3-tag w3-round-xlarge"><b></b></span>
            </div>
        </td>
    </tr>
</table>
</fieldset>
<br>
  <input type="text"    id="MSGOPEN"  readonly >
<br>
    <input type="text"    id="MSGCLOSE" readonly >

<br>
  <input type="text"    id="MSGREAD"  readonly>

<br>
    <input type="text"    id="MSGWRITE"  readonly>

<br>

<input class="w3-btn w3-blue-grey" type = "button" id="submitPage" value="valider"/>
<input type="reset" value="Reset Button">
<br><br>
    <div id='button'>
        <button type = "button"
            onclick="testConnect();">"test connection"</button>
    </div>
    <div id='button'>
        <button type = "button"
            onclick="sendText('hello');">"send text"</button>
    </div>
</form>

    Output:
    <form><textarea id="ExampleOutput" style="width:100%" rows="15"></textarea>

<script>

var websocket ;
var con = 0;
var IPJob = "";
var XMLbuffer = "";
var vFin = "";

function connect() {
  if(con == 0 )
    {
    IPJob ='ws://127.0.0.1:9200/';
    websocket = window.WebSocket || window.MozWebSocket;
        websocket = new WebSocket(IPJob,'myfancyprotocol');
        document.getElementById('MSGOPEN').value='';
    document.getElementById('MSGCLOSE').value='';
    document.getElementById('MSGREAD').value='';
    document.getElementById('MSGWRITE').value='';
    con =1;
    };

    websocket.onopen = function()
    {
        document.getElementById('MSGOPEN').value='Open Connection';
  };
  websocket.onclose = function()
    {
        document.getElementById('MSGCLOSE').value='End Connection';
    if ( con == 1) { con =0; setTimeout(function(){connect()},0); }
  };

  websocket.onmessage = function(event)
    {
    console.log(event.data);
        document.getElementById('MSGREAD').value='Websocket Message: read' ;
        alert(event.data)
  };

};

  function sendText(vFin)
  {
        websocket.send(vFin);  // ok for server
  };

function testConnect() {
    var readyState = websocket.readyState;
      if(readyState==1){
              // Send something to the socket
              document.getElementById('MSGOPEN').value='Open Connection';
            if(readyState>1){
                            document.getElementById('MSGCLOSE').value='End Connection';
      }
    }
};

connect();

</script>
</body>

</html>

I have image of the error sorry format html ??? no my source

https://www.zupimages.net/viewer.php?id=20/52/21yo.png