Is there a way to do a tcp connection to an IP with javascript?

前端 未结 3 419
名媛妹妹
名媛妹妹 2021-01-13 03:13

Let me give a little background on what I am trying to accomplish.

I have a device(chip and pin Terminal) that has a local IP address, It has been programmed to rece

3条回答
  •  余生分开走
    2021-01-13 03:27

    You cannot make a plain TCP connection from Javascript in a browser that will allow you to send data in your own data format or protocol. The browser simply does not support that.

    It only allows you to make Ajax requests and WebSocket connections. Both Ajax and WebSocket requests start life as an HTTP request. In the case of the webSocket request, the HTTP request can then be "upgraded" to the webSocket protocol after both sides agree, but the initial data sent to the server will be a legal HTTP request. You can see this MDN reference for a whole outline of how the webSocket protocol works from connection to actual packet format. Even once it is upgraded to the webSocket protocol, then it must use the webSocket framing format for all data which is described here.

    Here's an outline of the webSocket data frame format:

    0                   1                   2                   3
     0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
    +-+-+-+-+-------+-+-------------+-------------------------------+
    |F|R|R|R| opcode|M| Payload len |    Extended payload length    |
    |I|S|S|S|  (4)  |A|     (7)     |             (16/64)           |
    |N|V|V|V|       |S|             |   (if payload len==126/127)   |
    | |1|2|3|       |K|             |                               |
    +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
    |     Extended payload length continued, if payload len == 127  |
    + - - - - - - - - - - - - - - - +-------------------------------+
    |                               |Masking-key, if MASK set to 1  |
    +-------------------------------+-------------------------------+
    | Masking-key (continued)       |          Payload Data         |
    +-------------------------------- - - - - - - - - - - - - - - - +
    :                     Payload Data continued ...                :
    + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
    |                     Payload Data continued ...                |
    +---------------------------------------------------------------+
    

    So, unless your endpoint speaks HTTP or the webSocket protocol, you cannot connect directly to it from browser Javascript.

    What you are seeing in your question as the initial HTTP request is the beginnings of a webSocket connection. That's how it works.

    If you use Javascript in a non-browser environment such as node.js, you can use the the "net" module to create a plain TCP socket which you can then use whatever protocol you want with.

提交回复
热议问题