Javascript 使用javascript从浏览器连接到TCP Socket

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12407778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:54:39  来源:igfitidea点击:

Connecting to TCP Socket from browser using javascript

javascripthtmlnode.jssocketstcpclient

提问by swordfish

I have a vb.net application that opens a socket and listens on it.

我有一个 vb.net 应用程序,它打开一个套接字并监听它。

I need to communicate via this socket to that application using a javascript running on a browser. That is i need to send some data on this socket so that the app which is listening on this socket can take that data, do some stuff using some remote calls and get some more data and put it back on the socket that my javascript needs to read and print it in the browser.

我需要使用在浏览器上运行的 javascript 通过此套接字与该应用程序进行通信。那就是我需要在这个套接字上发送一些数据,以便在这个套接字上侦听的应用程序可以获取该数据,使用一些远程调用做一些事情并获取更多数据并将其放回我的 javascript 需要的套接字上在浏览器中阅读并打印它。

Ive tried, socket.io, websockify but none have proved to be useful.

我试过,socket.io,websockify 但没有一个被证明是有用的。

Hence the question, is what i am trying even possible? Is there a way that a javascript running in a browser can connect to a tcp socket and send some data and listen on it for some more data response on the socket and print it to the browser.

因此,问题是,我正在尝试的甚至可能吗?有没有办法让在浏览器中运行的 javascript 可以连接到 tcp 套接字并发送一些数据并监听它以获取套接字上的更多数据响应并将其打印到浏览器。

If this is possible can some one point me in the right direction as to which would help me establish the goal.

如果这是可能的,有人可以为我指出正确的方向,以帮助我建立目标。

回答by Robin Rizvi

As for your problem, currently you will have to depend on XHR or websockets for this.

至于你的问题,目前你将不得不依赖 XHR 或 websockets。

Currently no popular browser has implemented any such raw sockets api for javascript that lets you create and access raw sockets, but a draft for the implementation of raw sockets api in JavaScript is under-way. Have a look at these links:
http://www.w3.org/TR/raw-sockets/
https://developer.mozilla.org/en-US/docs/Web/API/TCPSocket

目前还没有流行的浏览器为 javascript 实现任何这样的原始套接字 api,允许您创建和访问原始套接字,但是在 JavaScript 中实现原始套接字 api 的草案正在进行中。看看这些链接:
http: //www.w3.org/TR/raw-sockets/
https://developer.mozilla.org/en-US/docs/Web/API/TCPSocket

Chrome now has support for raw TCP and UDP sockets in its ‘experimental' APIs. These features are only available for extensionsand, although documented, are hidden for the moment. Having said that, some developers are already creating interesting projects using it, such as this IRC client.

Chrome 现在在其“实验性”API 中支持原始 TCP 和 UDP 套接字。这些功能仅适用于扩展程序,尽管已记录在案,但目前处于隐藏状态。话虽如此,一些开发人员已经在使用它创建有趣的项目,例如这个 IRC 客户端

To access this API, you'll need to enable the experimental flag in your extension's manifest. Using sockets is pretty straightforward, for example:

要访问此 API,您需要在扩展程序的清单中启用实验标志。使用套接字非常简单,例如:

chrome.experimental.socket.create('tcp', '127.0.0.1', 8080, function(socketInfo) {
  chrome.experimental.socket.connect(socketInfo.socketId, function (result) {
        chrome.experimental.socket.write(socketInfo.socketId, "Hello, world!");         
    });
});

回答by Darren

This will be possible via the navigator interface as shown below:

这可以通过导航器界面实现,如下所示:

navigator.tcpPermission.requestPermission({remoteAddress:"127.0.0.1", remotePort:6789}).then(
  () => {
    // Permission was granted
    // Create a new TCP client socket and connect to remote host
    var mySocket = new TCPSocket("127.0.0.1", 6789);

    // Send data to server
    mySocket.writeable.write("Hello World").then(
        () => {

            // Data sent sucessfully, wait for response
            console.log("Data has been sent to server");
            mySocket.readable.getReader().read().then(
                ({ value, done }) => {
                    if (!done) {
                        // Response received, log it:
                        console.log("Data received from server:" + value);
                    }

                    // Close the TCP connection
                    mySocket.close();
                }
            );
        },
        e => console.error("Sending error: ", e)
    );
  }
);

More details are outlined in the w3.org tcp-udp-sockets documentation.

w3.org tcp-udp-sockets 文档中概述了更多详细信息。

http://raw-sockets.sysapps.org/#interface-tcpsocket

http://raw-sockets.sysapps.org/#interface-tcpsocket

https://www.w3.org/TR/tcp-udp-sockets/

https://www.w3.org/TR/tcp-udp-sockets/

Another alternative is to use Chrome Sockets

另一种选择是使用Chrome Sockets

Creating connections

创建连接

chrome.sockets.tcp.create({}, function(createInfo) {
  chrome.sockets.tcp.connect(createInfo.socketId,
    IP, PORT, onConnectedCallback);
});

Sending data

发送数据

chrome.sockets.tcp.send(socketId, arrayBuffer, onSentCallback);

Receiving data

接收数据

chrome.sockets.tcp.onReceive.addListener(function(info) {
  if (info.socketId != socketId)
    return;
  // info.data is an arrayBuffer.
});

You can use also attempt to use HTML5 Web Sockets(Although this is not direct TCP communication):

您也可以尝试使用HTML5 Web Sockets(虽然这不是直接的 TCP 通信):

var connection = new WebSocket('ws://IPAddress:Port');

connection.onopen = function () {
  connection.send('Ping'); // Send the message 'Ping' to the server
};

http://www.html5rocks.com/en/tutorials/websockets/basics/

http://www.html5rocks.com/en/tutorials/websockets/basics/

Your server must also be listening with a WebSocket server such as pywebsocket, alternatively you can write your own as outlined at Mozilla

您的服务器还必须使用 WebSocket 服务器(例如 pywebsocket)进行侦听,或者您可以按照Mozilla 中的概述编写自己的服务器

回答by chenyan

ws2sproject is aimed at bring socket to browser-side js. It is a websocket server which transform websocket to socket.

ws2s项目旨在将套接字引入浏览器端 js。它是一个将 websocket 转换为 socket 的 websocket 服务器。

ws2s schematic diagram

ws2s示意图

enter image description here

在此处输入图片说明

code sample:

代码示例:

var socket = new WS2S("wss://ws2s.feling.io/").newSocket()

socket.onReady = () => {
  socket.connect("feling.io", 80)
  socket.send("GET / HTTP/1.1\r\nHost: feling.io\r\nConnection: close\r\n\r\n")
}

socket.onRecv = (data) => {
  console.log('onRecv', data)
}

回答by AlikElzin-kilaka

See jsocket. Haven't used it myself. Been more than 3 years since last update (as of 26/6/2014).

请参阅jsocket。自己没用过。自上次更新以来已超过 3 年(截至 2014 年 6 月 26 日)。

* Uses flash :(

* 使用闪光灯 :(

From the documentation:

文档

<script type='text/javascript'>
    // Host we are connecting to
    var host = 'localhost'; 
    // Port we are connecting on
    var port = 3000;

    var socket = new jSocket();

    // When the socket is added the to document 
    socket.onReady = function(){
            socket.connect(host, port);             
    }

    // Connection attempt finished
    socket.onConnect = function(success, msg){
            if(success){
                    // Send something to the socket
                    socket.write('Hello world');            
            }else{
                    alert('Connection to the server could not be estabilished: ' + msg);            
            }       
    }
    socket.onData = function(data){
            alert('Received from socket: '+data);   
    }

    // Setup our socket in the div with the id="socket"
    socket.setup('mySocket');       
</script>

回答by Sdedelbrock

The solution you are really looking for is web sockets. However, the chromium project has developed some new technologies that are direct TCP connections TCP chromium

您真正要寻找的解决方案是网络套接字。但是,chromium 项目开发了一些新技术,即直接 TCP 连接TCPchromium

回答by Agi Hammerthief

In order to achieve what you want, you would have to write two applications (in either Java or Python, for example):

为了实现您想要的,您必须编写两个应用程序(例如,Java 或 Python):

  1. Bridge app that sits on the client's machine and can deal with both TCP/IP sockets and WebSockets. It will interact with the TCP/IP socket in question.

  2. Server-side app (such as a JSP/Servlet WAR) that can talk WebSockets. It includes at least one HTML page (including server-side processing code if need be) to be accessed by a browser.

  1. 位于客户端计算机上的桥接应用程序,可以处理 TCP/IP 套接字和 WebSocket。它将与有问题的 TCP/IP 套接字交互。

  2. 可以与 WebSockets 对话的服务器端应用程序(例如 JSP/Servlet WAR)。它至少包括一个可供浏览器访问的 HTML 页面(如果需要,还包括服务器端处理代码)。

It should work like this

它应该像这样工作

  1. The Bridge will open a WS connection to the web app (because a server can't connect to a client).
  2. The Web app will ask the client to identify itself
  3. The bridge client sends some ID information to the server, which stores it in order to identify the bridge.
    1. The browser-viewable page connects to the WS server using JS.
    2. Repeat step 3, but for the JS-based page
    3. The JS-based page sends a command to the server, including to which bridge it must go.
    4. The server forwards the command to the bridge.
    5. The bridge opens a TCP/IP socket and interacts with it (sends a message, gets a response).
    6. The Bridge sends a response to the server through the WS
    7. The WS forwards the response to the browser-viewable page
    8. The JS processes the response and reacts accordingly
    9. Repeat until either client disconnects/unloads
  1. Bridge 将打开到 Web 应用程序的 WS 连接(因为服务器无法连接到客户端)。
  2. Web 应用程序将要求客户端识别自己
  3. 网桥客户端向服务器发送一些 ID 信息,服务器存储这些信息以识别网桥。
    1. 浏览器可查看页面使用 JS 连接到 WS 服务器。
    2. 重复第 3 步,但针对基于 JS 的页面
    3. 基于 JS 的页面向服务器发送一个命令,包括它必须去哪个网桥。
    4. 服务器将命令转发到网桥。
    5. 网桥打开一个 TCP/IP 套接字并与之交互(发送消息,获得响应)。
    6. Bridge 通过 WS 向服务器发送响应
    7. WS 将响应转发到浏览器可查看的页面
    8. JS 处理响应并做出相应的反应
    9. 重复直到任一客户端断开连接/卸载

Note 1:The above steps are a vast simplification and do not include information about error handling and keepAlive requests, in the event that either client disconnects prematurely or the server needs to inform clients that it is shutting down/restarting.

注 1:上述步骤是一个极大的简化,不包括有关错误处理和 keepAlive 请求的信息,以防客户端过早断开连接或服务器需要通知客户端它正在关闭/重新启动。

Note 2:Depending on your needs, it might be possible to merge these components into one if the TCP/IP socket server in question (to which the bridge talks) is on the same machine as the server app.

注意 2:根据您的需要,如果有问题的 TCP/IP 套接字服务器(网桥与之通信)与服务器应用程序在同一台机器上,则可以将这些组件合并为一个。