【问题标题】:Websocket: javascript as client and python as server, and web host on LinuxWebsocket:javascript 作为客户端,python 作为服务器,Linux 上的 web 主机
【发布时间】:2016-08-22 23:03:41
【问题描述】:

我需要建立一个使用 Javascript 作为客户端语言的网站,以通过 websockets 与 python 服务器进行通信。该网站需要托管在 Linux 上。目前,我正在使用命令python -m SimpleHTTPServer 构建一个简单的服务器,该服务器也在Linux 上并使用python。

如何设置 javascript 客户端 websocket 通信?或者我应该如何处理架构?

【问题讨论】:

标签: javascript python websocket server tcp-ip


【解决方案1】:

假设您的 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);
    );

无论您的服务器是什么样的,您始终需要确保您的服务器和客户端使用相同的“协议”,即它们使用相同的变量来发送和发送它们的顺序。

如果你还需要在 python 中设置一个套接字服务器,我建议你看一些在线教程,因为这是一个不平凡的任务:http://www.binarytides.com/python-socket-server-code-example/

【讨论】:

  • 但是我只使用命令“python -m SimpleHTTPServer 8000”在Linux上托管我的网站并在Windows上通过172.XX.XX.XX:8000打开网站。并且似乎无法连接。
  • 您应该检查您是否没有启用防火墙。如果你去 localhost:8080 可以吗?
  • 顺便说一句,网站可以显示。
  • 请澄清。网站显示但“无法连接”?那么给出问题的确切命令是什么?
  • 我被你想通过 websockets 连接的印象所感动。如果您只想在计算机上运行 python 代码并将其输出到网站上。您可能想要安装 XAMPP(或 WAMPP)服务器设置。在这里查看最后一个答案:stackoverflow.com/questions/7460938/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-23
  • 2012-01-26
  • 1970-01-01
  • 2021-04-17
  • 2020-06-09
  • 1970-01-01
  • 2014-08-17
相关资源
最近更新 更多