WebSocket don't receive a response

WebSocket don't receive a response

Postby kea_ » Thu Oct 17, 2013 6:54 am

Hello together, I'm new to python.
I would write a little server (python) client (websocket) tool tor the raspberry pi.

First I have build a SocketServer and a SocketClient both written in python. If I run those programs they are working together.
Then I have build the WebSocket. The WebSocket can send the question to the SocketServer and the SocketServer send an answer to the WebSocket. But the WebSocket seems not to recognize that there is an answer. Could it be that the Python Socket not sending all data?

SocketServer
Code: Select all
#! /usr/bin/python3

from socket import *
import threading
import time
import re


# CLASSES

class CSocketServer:
    def __init__(self, host, port):
        self.socket = socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.bind((host, port))
        self.host = host
        self.port = port
       
    def __del__(self):   
        self.socket.close()
       
    def listen(self):
        self.socket.listen(5) #5 denotes the number of clients can queue
        while True:
            print("Waiting for connection on " + self.host + ":" + str(self.port) + "...")
            connection, address = self.socket.accept()
            socket = CSocket(connection, address)
            socket.start()
        return
   

class CSocket (threading.Thread):
    def __init__(self, socket, address):
        threading.Thread.__init__(self)
        self.socket = socket
        self.host = address[0]
        self.port = address[1]
        self.address = address
        self.isRunning = True

    # !!! THIS IS THE FUNCTION FOR COMMUNICATE WITH THE CLIENT. !!!
    def run(self):
        message = []
        print("New connection: " + self.host + ":" + str(self.port))
        self.handshake()
        #self.send('\x00hello\xff')
        self.send("Hallo von Heiko")
        return


    def handshake(self):
        msg = []
        self.receive(msg)
        key = self.getSecWebSocketKey(msg[0])
                       
        msg = ''.join(('HTTP/1.1 101 Switching Protocols\n',
                       'Upgrade: websocket\n',
                       'Connection: Upgrade\n',
                       'Sec-WebSocket-Accept: ' + key + '\n',
                       'Sec-WebSocket-Protocol: chat'))                       
        self.send(msg)
       
       
    def stop(self):
        self.isRunning = False
        return


    def getSecWebSocketKey(self, header):
        r = re.search('Sec-WebSocket-Key:\s+(.*?)[\n\r]+', header)
        if r == None:
            return ""
        else:
            return r.groups()[0].strip()
        return ""
   
   
    def send(self, message):
        print("Send:\n'" + message + "'")
        #self.socket.sendall('\x00' + message.encode('utf-8') + '\xff')
        self.socket.sendall(message.encode('utf-8'))
        return

   
    def receive(self, message):
        data = self.socket.recv(1024)
        if not data: return False
        message.append(data.decode('utf-8'))
        print("Received:\n'" + message[0] + "'")
        return True
   
# MAIN
if __name__ == "__main__":
    host = 'localhost'
    port = 9999

    socketServer = CSocketServer(host, port)
    socketServer.listen()




SocketClient this works :D
Code: Select all
#! /usr/bin/python3

from socket import *
import re

def send(socket, msg):
    print("Send:\n" + msg + "\n")
    socket.sendall(msg.encode('utf-8'))
    return
   
def receive(socket, msg):
    data = socket.recv(1024)
    if not data: return False
    msg.append(data.decode('utf-8'))
    print("Received:\n" + msg[0] + "\n")
    return True

def handshake(socket):
    msg = ''.join(('GET /chat HTTP/1.1\n',
                   'Host: server.example.com\n',
                   'Upgrade: websocket\n',
                   'Connection: Upgrade\n',
                   'Sec-WebSocket-Key: Sprinkler-Client\n',
                   'Origin: http://127.0.0.1:9999\n',
                   'Sec-WebSocket-Protocol: chat, superchat\n',
                   'Sec-WebSocket-Version: 13'))
    send(socket, msg)
   
# MAIN
if __name__ == "__main__":
    host = '127.0.0.1' # '127.0.0.1' can also be used
    port = 9999
 
    socket = socket()
    socket.connect((host, port))
   
    message = []
    handshake(socket)
    receive(socket, message)
       
    socket.close()


WebSocket this doesn't work... :?:
Code: Select all
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>WebSocket Test</title>
        <script language="javascript" type="text/javascript"> 
            //var wsUri = "ws://echo.websocket.org/";
            var wsUri = "ws://localhost:9999/";
            var output; 

            function init() {
                output = document.getElementById("output");
                testWebSocket();
            } 

            function testWebSocket() {
                websocket = new WebSocket(wsUri);
                websocket.onopen = function(evt) { onOpen(evt) };
                websocket.onclose = function(evt) { onClose(evt) };
                websocket.onmessage = function(evt) { onMessage(evt) };
                websocket.onerror = function(evt) { onError(evt) };
            } 

            function onOpen(evt) {
                writeToScreen("CONNECTED");
                doSend("WebSocket rocks");
            } 

            function onClose(evt) {
                writeToScreen("DISCONNECTED");
            } 

            function onMessage(evt) {
                writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>');
                //websocket.close();
            } 

            function onError(evt) {
                writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
            } 

            function doSend(message) {
                writeToScreen("SENT: " + message);  websocket.send(message);
            } 

            function writeToScreen(message) {
                var pre = document.createElement("p");
                pre.style.wordWrap = "break-word";
                pre.innerHTML = message;
                output.appendChild(pre);
            } 

            window.addEventListener("load", init, false); 
        </script> 
    </head>
    <body>
        <h2>WebSocket Test</h2>  <div id="output"></div>  </html>
    </body>
</html>


Thanks for your answer
Heiko
Last edited by Mekire on Thu Oct 17, 2013 6:58 am, edited 1 time in total.
Reason: First post lock.
kea_
 
Posts: 1
Joined: Thu Oct 17, 2013 6:26 am

Return to Networking

Who is online

Users browsing this forum: No registered users and 2 guests