使用javascrip从浏览器连接到TCP套接字

2024-03-28 09:57:51 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

至于您的问题,目前您必须依赖XHR或WebSocket来解决。

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

Chrome现在在其“实验”api中支持原始的TCP和UDP套接字。这些功能仅适用于扩展,尽管有文档记录,但暂时隐藏。尽管如此,一些开发人员已经在使用它创建有趣的项目,例如this IRC client

要访问此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!");         
    });
});

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

ws2s原理图

enter image description here

代码示例:

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)
}

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

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)
    );
  }
);

更多细节在w3.org tcp udp sockets文档中概述。

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

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

另一种选择是使用Chrome Sockets

创建连接

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

发送数据

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

接收数据

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

也可以尝试使用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/

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

相关问题 更多 >