KevinLu KevinLu - 1 year ago 267
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 Source

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://');
socket.onopen= function() {
socket.onmessage= function(s) {
    alert('got reply '+s);

Or via

navigator.tcpPermission.requestPermission({remoteAddress:"", remotePort:6789}).then(
  () => {
    // Permission was granted
    // Create a new TCP client socket and connect to remote host
    var mySocket = new TCPSocket("", 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");
                ({ value, done }) => {
                    if (!done) {
                        // Response received, log it:
                        console.log("Data received from server:" + value);

                    // Close the TCP connection
        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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download