Websocket:javascript 作为客户端,python 作为服务器,Web 主机在 Linux
Websocket: javascript as client and python as server, and web host on Linux
我需要建立一个网站,其中使用 Javascript 作为客户端语言通过 websockets 与 python 服务器通信。该网站需要托管在 Linux 上。现在,我正在使用命令 python -m SimpleHTTPServer
构建一个简单的服务器,服务器也在 Linux 上并使用 python。
如何设置 javascript 客户端 websocket 通信?或者我应该如何处理架构?
假设您的 python websocket 服务器已启动 运行。您可以通过 html5:
通过您的网站连接它
socket= new WebSocket('ws://www.example.com:8000/somesocket');
socket.onopen= function() {
socket.send('hello');
};
socket.onmessage= function(s) {
alert('got reply '+s);
};
或通过
http://raw-sockets.sysapps.org/#interface-tcpsocket
https://www.w3.org/TR/tcp-udp-sockets/
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);
);
无论您的服务器是什么样子,您始终需要确保您的服务器和客户端使用相同的 "protocol",即它们使用相同的变量来发送和发送它们的顺序。
如果您还需要在 python 中设置套接字服务器,我建议您在线查看一些教程,因为这是一项非常重要的任务:http://www.binarytides.com/python-socket-server-code-example/
我需要建立一个网站,其中使用 Javascript 作为客户端语言通过 websockets 与 python 服务器通信。该网站需要托管在 Linux 上。现在,我正在使用命令 python -m SimpleHTTPServer
构建一个简单的服务器,服务器也在 Linux 上并使用 python。
如何设置 javascript 客户端 websocket 通信?或者我应该如何处理架构?
假设您的 python websocket 服务器已启动 运行。您可以通过 html5:
通过您的网站连接它socket= new WebSocket('ws://www.example.com:8000/somesocket');
socket.onopen= function() {
socket.send('hello');
};
socket.onmessage= function(s) {
alert('got reply '+s);
};
或通过
http://raw-sockets.sysapps.org/#interface-tcpsocket
https://www.w3.org/TR/tcp-udp-sockets/
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);
);
无论您的服务器是什么样子,您始终需要确保您的服务器和客户端使用相同的 "protocol",即它们使用相同的变量来发送和发送它们的顺序。
如果您还需要在 python 中设置套接字服务器,我建议您在线查看一些教程,因为这是一项非常重要的任务:http://www.binarytides.com/python-socket-server-code-example/