Willem van Opstal
Willem van Opstal

Reputation: 313

Send string to python websocket using JavaScript

I have a locally running python websocket (code below) which I let run infinitely. I mainly copied the code from an example. The example uses another python client script to send data to it (also below). That simply works like a charm and is very simple; just what I need since I have some experience in Python but no clue about the 'web/internet'-thingies.

Now, in stead of using the python client, I'd like to send a message from an html document by javascript. Is there any guidance into a short piece of 'stupid' code, just sending one message (string) to the python websocketserver? The python script would then be able to execute different processes using this data.

Python server: (works :) )

from socket import *

host = "localhost"
port = 8089
buf = 1024
addr = (host,port)

sock = socket(AF_INET,SOCK_DGRAM)
sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
sock.bind(addr)

print "Websocket active."
print "address:\t"+host+":"+str(port)

while 1:
    data,addr = sock.recvfrom(buf)
    if not data:
        print "Client has exited!"
        break
    else:
        print "\nReceived message '", data,"'"

# Close socket
sock.close()

Python Client ( works, but not needed)

from socket import *

host = "localhost"
port = 8089
buf = 1024
addr = (host,port)

sock = socket(AF_INET,SOCK_DGRAM)
def_msg = "===Enter message to send to server===";
print "\n",def_msg

while (1):
    data = raw_input('>> ')
    if not data:
        break
    else:
        if(sock.sendto(data,addr)):
            print "Sending message '",data,"'....."

sock.close()

And now towards the Javascript client..
Can't it be as simple as this? ;

var socket = new WebSocket("ws://localhost:8089");
socket.onopen = function () {
    alert("alerting you");
    socket.send('Pingel');
};

Upvotes: 3

Views: 3954

Answers (1)

robertklep
robertklep

Reputation: 203304

Your Python server implements a regular TCP server, but your JS code is acting as a WebSocket client, which is an actual proper protocol on top of TCP: https://www.rfc-editor.org/rfc/rfc6455

If you want both ends to communicate properly, you need to run a WebSocket server, like this: https://github.com/dpallot/simple-websocket-server

Upvotes: 3

Related Questions