KevinLu KevinLu - 3 months ago 79
Javascript Question

Websocket: javascript as client and python as server, and web host on Linux

I need to build the website and use the javascript as client language to communicate with python server. BTW, the webpage need to be host on Linux. and for now, I just only use the command "python -m SimpleHTTPServer" to build a simple server. and the server is also on the Linux and use the python. could anyone kindly to teach me how to build this system and how to communicate javascript and python by websocket? thanks you!

Answer

Assuming that your python websocket server is up an running. You can connect with it through your website through either html5:

socket= new WebSocket('ws://www.example.com:8000/somesocket');
socket.onopen= function() {
    socket.send('hello');
};
socket.onmessage= function(s) {
    alert('got reply '+s);
};

Or via

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

Whatever your server looks like, you always need to make sure your server and client use the same "protocol", i.e. they use the same variables to send and order in which to send them.

If you also need to set up a socket server in python, I suggest you look at some tutorials online as this is a non-trivial task: http://www.binarytides.com/python-socket-server-code-example/