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)
);
}
);
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
};
至于您的问题,目前您必须依赖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,您需要在扩展的清单中启用实验标志。使用套接字非常简单,例如:
ws2s项目旨在将socket引入浏览器端js。它是一个websocket服务器,将websocket转换为socket。
ws2s原理图
代码示例:
这可以通过导航器界面实现,如下所示:
更多细节在w3.org tcp udp sockets文档中概述。
http://raw-sockets.sysapps.org/#interface-tcpsocket
https://www.w3.org/TR/tcp-udp-sockets/
另一种选择是使用Chrome Sockets
创建连接
发送数据
接收数据
也可以尝试使用
HTML5 Web Sockets
(尽管这不是直接的TCP通信):http://www.html5rocks.com/en/tutorials/websockets/basics/
您的服务器还必须使用WebSocket服务器(如pywebsocket)进行侦听,或者您也可以按照Mozilla中的说明编写自己的服务器
相关问题 更多 >
编程相关推荐