示例#1
0
def accept_conn(listen_sock):
    global client_s
    cl, remote_addr = listen_sock.accept()

    if not server_handshake(cl):
        send_html(cl)
        return False

    prev = os.dupterm(None)
    os.dupterm(prev)
    if prev:
        print("\nConcurrent WebREPL connection from", remote_addr, "rejected")
        cl.close()
        return False
    print("\nWebREPL connection from:", remote_addr)
    client_s = cl

    ws = websocket.websocket(cl, True)
    ws = _webrepl._webrepl(ws)
    cl.setblocking(False)
    # notify REPL on socket incoming data (ESP32/ESP8266-only)
    if hasattr(os, "dupterm_notify"):
        cl.setsockopt(socket.SOL_SOCKET, 20, os.dupterm_notify)
    os.dupterm(ws)

    return True
示例#2
0
 def __init__(self, poller, client_socket):
     self._socket = client_socket
     self.ws = websocket.websocket(client_socket, True)
     self.fileno = client_socket.fileno()
     # poller.register doesn't complain if you register ws but it fails when you call ipoll.
     poller.register(client_socket,
                     select.POLLIN | select.POLLERR | select.POLLHUP)
示例#3
0
 def setup(self, sock, addr, close_callback):
     self.address = addr
     self._s = sock
     self.ws = websocket(self._s, True)
     self._close_clb = close_callback
     sock.setblocking(False)
     sock.setsockopt(socket.SOL_SOCKET, 0x14, self.notify)
示例#4
0
def WSReader(reader, writer):
    webkey = None
    while 1:
        line = yield from reader.readline()
        print(line)
        if not line:
            raise ValueError()
        if line == b"\r\n":
            break
        if line.startswith(b'Sec-WebSocket-Key'):
            webkey = line.split(b":", 1)[1]
            webkey = webkey.strip()

    if not webkey:
        raise ValueError("Not a websocker request")

    respkey = make_respkey(webkey)

    await writer.awrite(b"""\
HTTP/1.1 101 Switching Protocols\r
Upgrade: websocket\r
Connection: Upgrade\r
Sec-WebSocket-Accept: """)
    await writer.awrite(respkey)
    # This will lead to "<key>\n\r\n" being written. Not exactly
    # "\r\n\r\n", but browsers seem to eat it.
    await writer.awrite("\r\n")
    # await writer.awrite("\r\n\r\n")

    print("Finished websocket handshake")
    ws = websocket.websocket(reader.ios)
    print("uasyncio.StreamReader(reader.ios, ws)")
    rws = uasyncio.StreamReader(reader.ios, ws)

    return rws
示例#5
0
def create_websocket(addr):
    s = socket.socket()
    s.connect(addr)
    #s = s.makefile("rwb")
    websocket_helper.client_handshake(s)
    ws = websocket(s)
    return ws
示例#6
0
文件: uremi.py 项目: pfalcon/uremi
 def http_handler(self, s, req):
     meth, path, proto = req.split()
     if path == b"/":
         server.skip_headers(s)
         s.write("HTTP/1.0 200 OK\r\n\r\n")
         render(self.w, s)
     elif path == b"/res/style.css":
         server.skip_headers(s)
         s.write("HTTP/1.0 200 OK\r\n\r\n")
         with open(path[1:], "rb") as f:
             data = f.read()
             s.write(data)
     elif path == b"/ws":
         websocket_helper.server_handshake(s)
         s = websocket.websocket(s)
         print("websock connected")
         while 1:
             data = s.readline()
             data = data.decode("ascii").rstrip().split()
             print(data)
             global CONN
             CONN = s
             EVENT_MAP[(int(data[0]), data[1])]()
     else:
         s.write("HTTP/1.0 404 NAK\r\n\r\n")
示例#7
0
文件: ws.py 项目: pmp-p/fel-installer
    def switch(self, ct, mtu_rx, mtu_tx=125):
        self.client.setblocking(False)
        if ct == 'ws':
            self.ws = websocket.websocket(self.client, True)
            if mtu_tx > self.WS_MTU:
                print(
                    "180: not using user MTU [%s] because rsv not implemented and mode is websocket"
                    % mtu_rx)

            self.RX = self.RX_ws
            self.TX = self.TX_ws
            #max receive
            self.RX_MTU = mtu_rx
        else:
            print('205: standard socket, mtu=', mtu_rx)
            self.RX = self.RX_std
            self.TX = self.TX_std
            #max receive
            self.RX_MTU = mtu_rx
            #but limit send
            mtu = mtu_tx

        self.TX_MTU = mtu_tx
        self.BO = self.RX_MTU * 4

        self.errcnt = 0
        self.log = []
示例#8
0
def _accept_conn(server_fd):
    global _client_fd
    global ws
    _client_fd, remote_addr = server_fd.accept()
    print("websocket client from: ", remote_addr)
    _client_fd.setblocking(False)
    _client_fd.setsockopt(socket.SOL_SOCKET, 20, handshake_callback)
    ws = websocket.websocket(_client_fd, True)
示例#9
0
 def accept_conn(self, listen_sock):
     cl, remote_addr = listen_sock.accept()
     print("\nWebSocket connection from:", remote_addr)
     websocket_helper.server_handshake(cl)
     self.ws = websocket.websocket(cl, True)
     self.ws.ioctl(9, 2)  # change to data frame
     cl.setblocking(False)
     self.client_s = cl
     self.connected = True
示例#10
0
def accept_ws(listen_sock):
    global client_s
    cl, remote_addr = listen_sock.accept()
    client_s.append(cl)

    websocket_helper.server_handshake(cl)
    ws = websocket.websocket(cl, True)
    cl.setblocking(False)
    cl.setsockopt(socket.SOL_SOCKET, 20, uos.dupterm_notify)
    uos.dupterm(ws)
示例#11
0
 def run(self):
     while True:
         conn, addr = self.s.accept()
         try:
             c = websocket(conn, addr)
             print('Connected by', addr[1])
             self.users.append(c)
             threading.Thread(target=self.process, args=((c, ))).start()
         except Exception:
             pass
示例#12
0
	def __init__(self, conn, addr, s, on_close):
		print("Start of init")
		self.conn = conn
		self.addr = addr
		self.s = s
		self.on_close = on_close
		self.ws = websocket(s, True)
		self.process()
		self.client_close = False
		print("End of init")
    def __init__(self, addr, s, close_callback):
        self.client_close = False

        self.address = addr
        self.socket = s
        self.ws = websocket(s, True)
        self.close_callback = close_callback

        s.setblocking(False)
        s.setsockopt(socket.SOL_SOCKET, 20, self.notify)
def main():

    if len(sys.argv) != 3:
        help(1)

    if ":" in sys.argv[1] and ":" in sys.argv[2]:
        error("Operations on 2 remote files are not supported")
    if ":" not in sys.argv[1] and ":" not in sys.argv[2]:
        error("One remote file is required")

    if ":" in sys.argv[1]:
        op = "get"
        host, port, src_file = parse_remote(sys.argv[1])
        dst_file = sys.argv[2]
        if os.path.isdir(dst_file):
            basename = src_file.rsplit("/", 1)[-1]
            dst_file += "/" + basename
    else:
        op = "put"
        host, port, dst_file = parse_remote(sys.argv[2])
        src_file = sys.argv[1]
        if dst_file[-1] == "/":
            basename = src_file.rsplit("/", 1)[-1]
            dst_file += basename

    if 1:
        print(op, host, port)
        print(src_file, "->", dst_file)

    s = socket.socket()

    ai = socket.getaddrinfo(host, port)
    addr = ai[0][4]

    s.connect(addr)
    #s = s.makefile("rwb")
    websocket_helper.client_handshake(s)

    ws = websocket(s)

    import getpass
    passwd = getpass.getpass()
    login(ws, passwd)
    print("Remote WebREPL version:", get_ver(ws))

    # Set websocket to send data marked as "binary"
    ws.ioctl(9, 2)

    if op == "get":
        get_file(ws, dst_file, src_file)
    elif op == "put":
        put_file(ws, src_file, dst_file)

    s.close()
示例#15
0
    def __init__(self, addr, s, close_callback):
        self.client_close = False
        self._need_check = False

        self.address = addr
        self.socket = s
        self.ws = websocket(s, True)
        self.close_callback = close_callback

        s.setblocking(False)
        s.setsockopt(socket.SOL_SOCKET, 20, self.notify)
示例#16
0
def accept_conn(listen_sock):
    global client_s
    cl, remote_addr = listen_sock.accept()
    client_s = cl
    websocket_helper.server_handshake(cl)
    ws = websocket.websocket(cl, True)
    cl.setblocking(False)
    # notify REPL on socket incoming data
    cl.setsockopt(socket.SOL_SOCKET, 20, uos.dupterm_notify)
    uos.dupterm(ws)
    print("WebREPL connected\n>>> ", end="")
示例#17
0
    def __init__(self, addr: str, s: socket, close_callback):
        self.client_close = False
        self._need_check = False

        self.address = addr
        self.socket = s
        self.ws = websocket(s, True)
        self.poll = uselect.poll()
        self.close_callback = close_callback

        self.socket.setblocking(False)
        self.poll.register(self.socket, uselect.POLLIN)
示例#18
0
    def connect(self, host, port):
        self.debugmsg("[d] connecting to %s %s" % (host, port))
        self.s = socket.socket()
        ai = socket.getaddrinfo(host, port)
        addr = ai[0][4]
        #self.debugmsg("connecting to adr %r" % addr)

        self.s.connect(addr)
        #s = s.makefile("rwb")
        self.debugmsg("[d] handshake")
        self.client_handshake(self.s)
        self.ws = websocket(self.s)
        self.ws.debug = self.debug
示例#19
0
    def __init__(self,
                 address,
                 loglevel=logging.INFO,
                 ssl_args=None,
                 max_join_time=2.0,
                 backlog_size=32,
                 **kwargs):
        """
        Constructor for a simple web socket server.

        `address` is a (hostname, port) tuple to bind the web socket to.

        `loglevel` values should be imported from the logging module.
        logging.INFO only shows server start/stop messages, logging.DEBUG shows
        clients (dis)connecting and messages being sent/received.

        `protocols` and `extensions` are passed directly to the websocket
        constructor.

        `ssl_args` is a dictionary with arguments for `websocket.enable_ssl`
        (and thus to ssl.wrap_socket).  If omitted, the server is not
        SSL-enabled. If specified, at least the dictionary keys "keyfile" and
        "certfile" must be present because these are required arguments for
        `websocket.enable_ssl` for a server socket.

        `max_join_time` is the maximum time (in seconds) to wait for client
        responses after sending CLOSE frames, it defaults to 2 seconds.

        `backlog_size` is directly passed to `websocket.listen`.
        """
        logging.basicConfig(level=loglevel,
                            format='%(asctime)s: %(levelname)s: %(message)s',
                            datefmt='%H:%M:%S')

        scheme = 'wss' if ssl_args else 'ws'
        hostname, port = address
        logging.info('Starting server at %s://%s:%d', scheme, hostname, port)

        self.sock = websocket(**kwargs)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        if ssl_args:
            self.sock.enable_ssl(server_side=True, **ssl_args)

        self.sock.bind(address)
        self.sock.listen(backlog_size)

        self.max_join_time = max_join_time
示例#20
0
def accept_conn(listen_sock):
    global client_s
    cl, remote_addr = listen_sock.accept()
    if uos.dupterm():
        print("\nConcurrent WebREPL connection from", remote_addr, "rejected")
        cl.close()
        return
    print("\nWebREPL connection from:", remote_addr)
    client_s = cl
    websocket_helper.server_handshake(cl)
    ws = websocket.websocket(cl, True)
    ws = _webrepl._webrepl(ws)
    cl.setblocking(False)
    # notify REPL on socket incoming data
    cl.setsockopt(socket.SOL_SOCKET, 20, uos.dupterm_notify)
    uos.dupterm(ws)
示例#21
0
文件: webrepl.py 项目: ccldaout/esp32
def accept_conn(listen_sock):
    global client_s
    cl, remote_addr = listen_sock.accept()
    prev = uos.dupterm(None)
    uos.dupterm(prev)
    if prev:
        print("\nConcurrent WebREPL connection from", remote_addr, "rejected")
        cl.close()
        return
    print("\nWebREPL connection from:", remote_addr)
    client_s = cl
    websocket_helper.server_handshake(cl)
    ws = websocket.websocket(cl, True)
    ws = _webrepl._webrepl(ws)
    cl.setblocking(False)
    uos.dupterm(ws)
示例#22
0
def accept_conn(listen_sock):
    global client_s
    cl, remote_addr = listen_sock.accept()
    if uos.dupterm():
        print("\nConcurrent WebREPL connection from", remote_addr, "rejected")
        cl.close()
        return
    print("\nWebREPL connection from:", remote_addr)
    client_s = cl
    websocket_helper.server_handshake(cl)
    ws = websocket.websocket(cl, True)
    ws = _webrepl._webrepl(ws)
    cl.setblocking(False)
    # notify REPL on socket incoming data
    cl.setsockopt(socket.SOL_SOCKET, 20, uos.dupterm_notify)
    uos.dupterm(ws)
示例#23
0
文件: server.py 项目: taddeus/wspy
    def __init__(self, address, loglevel=logging.INFO, ssl_args=None,
                 max_join_time=2.0, backlog_size=32, **kwargs):
        """
        Constructor for a simple web socket server.

        `address` is a (hostname, port) tuple to bind the web socket to.

        `loglevel` values should be imported from the logging module.
        logging.INFO only shows server start/stop messages, logging.DEBUG shows
        clients (dis)connecting and messages being sent/received.

        `protocols` and `extensions` are passed directly to the websocket
        constructor.

        `ssl_args` is a dictionary with arguments for `websocket.enable_ssl`
        (and thus to ssl.wrap_socket).  If omitted, the server is not
        SSL-enabled. If specified, at least the dictionary keys "keyfile" and
        "certfile" must be present because these are required arguments for
        `websocket.enable_ssl` for a server socket.

        `max_join_time` is the maximum time (in seconds) to wait for client
        responses after sending CLOSE frames, it defaults to 2 seconds.

        `backlog_size` is directly passed to `websocket.listen`.
        """
        logging.basicConfig(level=loglevel,
                format='%(asctime)s: %(levelname)s: %(message)s',
                datefmt='%H:%M:%S')

        scheme = 'wss' if ssl_args else 'ws'
        hostname, port = address
        logging.info('Starting server at %s://%s:%d', scheme, hostname, port)

        self.sock = websocket(**kwargs)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        if ssl_args:
            self.sock.enable_ssl(server_side=True, **ssl_args)

        self.sock.bind(address)
        self.sock.listen(backlog_size)

        self.max_join_time = max_join_time
示例#24
0
    def accept_conn(cls, listen_sock):

        cl, remote_addr = listen_sock.accept()
        prev = uos.dupterm(None)
        uos.dupterm(prev)
        if prev:
            print("\nConcurrent WebREPL connection from", remote_addr,
                  "rejected")
            cl.close()
            return
        print("\nWebREPL connection from:", remote_addr)
        WebREPL().client_s = cl
        websocket_helper.server_handshake(cl)
        WebREPL().ws = websocket.websocket(cl, True)

        WebREPL().wr = _webrepl._webrepl(WebREPL().ws)
        type(WebREPL().wr)
        cl.setblocking(False)
        # notify REPL on socket incoming data
        cl.setsockopt(socket.SOL_SOCKET, 20, uos.dupterm_notify)
        uos.dupterm(WebREPL().wr)
示例#25
0
def WSReader(reader, writer):

        webkey = None
        while 1:
            l = yield from reader.readline()
            print(l)
            if not l:
                raise ValueError()
            if l == b"\r\n":
                break
            if l.startswith(b'Sec-WebSocket-Key'):
                webkey = l.split(b":", 1)[1]
                webkey = webkey.strip()

        if not webkey:
            raise ValueError("Not a websocker request")

        respkey = make_respkey(webkey)

        await writer.awrite(b"""\
HTTP/1.1 101 Switching Protocols\r
Upgrade: websocket\r
Connection: Upgrade\r
Sec-WebSocket-Accept: """)
        await writer.awrite(respkey)
        # This will lead to "<key>\n\r\n" being written. Not exactly
        # "\r\n\r\n", but browsers seem to eat it.
        await writer.awrite("\r\n")
        #await writer.awrite("\r\n\r\n")

        print("Finished webrepl handshake")

        ws = websocket.websocket(reader.ios)
        rws = uasyncio.StreamReader(reader.ios, ws)

        return rws
示例#26
0
from websocket import websocket
from connection import Connection
from message import TextMessage
from errors import SocketClosed


if __name__ == '__main__':
    if len(sys.argv) < 3:
        print >> sys.stderr, 'Usage: python %s HOST PORT' % sys.argv[0]
        sys.exit(1)

    host = sys.argv[1]
    port = int(sys.argv[2])

    sock = websocket()
    sock.connect((host, port))
    sock.settimeout(1.0)
    conn = Connection(sock)

    try:
        try:
            while True:
                msg = TextMessage(raw_input())
                print 'send:', msg
                conn.send(msg)

                try:
                    print 'recv:', conn.recv()
                except socket.timeout:
                    print 'no response'
示例#27
0
def socket_handler(listen_s):
    gc.collect()

    try:
        client, remote_addr = listen_s.accept()
        if not client.readline() == b'GET / HTTP/1.1\r\n':
            client.close()
            return

        ws = None
        ws_key = None

        while True:
            line = client.readline()
            if line == b'\r\n' or line == b'':
                break
            h, v = [x.strip() for x in line.split(b':', 1)]
            if h == b'Connection':
                if v == b'Upgrade':
                    ws = True
            elif h == b'Sec-WebSocket-Key':
                ws_key = v
            print(v, h)
        if not ws:
            client.close()
            return
        print('Got valid socket connection from', remote_addr)
        d = uhashlib.sha1(ws_key)
        d.update(b'258EAFA5-E914-47DA-95CA-C5AB0DC85B11')
        client.send(b'\\n'
                    b'HTTP/1.1 101 Switching Protocols\r\n'
                    b'Upgrade: websocket\r\n'
                    b'Connection: Upgrade\r\n'
                    b'Sec-WebSocket-Accept: ')
        client.send(ubinascii.b2a_base64(d.digest())[:-1])
        client.send(b'\r\n\r\n')
        ws = websocket.websocket(client)

        def socket_handler_inner(client):
            global settings
            cmd = ws.readline().strip()
            if len(cmd) == 0:
                ws.close()
                client.close()
                return
            elif cmd == b'get':
                ws.write(json.dumps(settings))
                ws.write(b'OK\n')
            elif cmd == b'set':
                settings = json.loads(ws.readline())
                ws.write(b'OK\n')
            elif cmd == b'exec':
                try:
                    exec(ws.readline())
                    ws.write(b'OK\n')
                except Exception as e:
                    print('error', e)
                    ws.write(b'ERROR\n')
                    ws.write(json.dumps(repr(e)))
                    ws.write(b'\n')
            else:
                ws.write(b'ERROR\nUnknown action')
                ws.write(cmd)
                ws.write(b'\n')

        client.setblocking(False)
        client.setsockopt(socket.SOL_SOCKET, 20, socket_handler_inner)
        gc.collect()
    except Exception as e:
        print('Error handing socket:', e)
示例#28
0
def ws_write(msg, sz):
    s = uio.BytesIO()
    ws = websocket.websocket(s)
    ws.write(msg)
    s.seek(0)
    return s.read(sz)
                return
              if(index[1]['pState']=='false'):
                #send(read("ir_Data/Ac_btn-off"))
                mq.publish({"pState":"Flase"},'mi')
       
                return
        except:
          print("miot err")
webrepl.start()
time.sleep(2)
lib.update_time()

blinker.DEBUG=1
mq=blinker.blinker("fbc6da5da621",cb,'light')
mq.connect()
ws=websocket.websocket(81)
 
 
ms="" 

def ccb(msg):
       global ms
       time.sleep_ms(100)
       msg=eval(msg)
       msg={'data': [list(msg["data"].keys())[0], msg["data"][list(msg["data"].keys())[0]]], 'deviceType': 'DiyArduino'}
       print("websocket:",msg,"\n",type(msg))
       #print("websocket1:",msg)
       cb("websocket",msg   )

def web():
  global th
示例#30
0
                 b'Sec-WebSocket-Version: 13\r\n'
                 b'Sec-Websocket-Protocol: mqtt\r\n'
                 b'\r\n'))

        # TODO: Validate the response to the websocket upgrade request.  This
        # can be done by checking the HTTP response code and validating the
        # "Sec-WebSocket-Accept" header.
        line = s.readline()
        while line:
            if line == b'\r\n':
                break
            line = s.readline()

        # Now that the WebSocket protocol upgrade negotiation is complete,
        # create a WebSocket from the TCP socket connected to the MQTT broker.
        ws = websocket(s, is_client=True)

        # Create an MQTT client.
        client_id = hexlify(bytes([getrandbits(8) for _ in range(8)]))
        client = MQTTClient(client_id, sock=ws, keepalive=keepalive)

        # This is the callback function that is invoked when a message is
        # received.  It parses the message looking for a valid RGB tuple, and
        # sends it to the NeoPixels.
        def on_message_received(topic, message):
            print('Message received: topic=%s, message=%s' % (topic, message))
            message = message.decode('ascii')
            elements = message.split(':')
            if len(elements) == 2 and elements[0] == 'C':
                rgb_tuple = elements[1]
                rgb_tuple = rgb_tuple.split(',')
示例#31
0
def register(client_socket):
    ws = websocket.websocket(client_socket, True)
    # poller.register doesn't complain if you register ws but it fails when you call ipoll.
    poller.register(client_socket, select.POLLIN)
    clients[client_socket.fileno()] = ws
示例#32
0
print(ws_read(b"\x80\x04ping", 4))  # FRAME_CONT
print(ws_write(b"pong", 6))

# split frames are not supported
# print(ws_read(b"\x01\x04ping", 4))

# extended payloads
print(ws_read(b'\x81~\x00\x80' + b'ping' * 32, 128))
print(ws_write(b"pong" * 32, 132))

# mask (returned data will be 'mask' ^ 'mask')
print(ws_read(b"\x81\x84maskmask", 4))

# close control frame
s = uio.BytesIO(b'\x88\x00')  # FRAME_CLOSE
ws = websocket.websocket(s)
print(ws.read(1))
s.seek(2)
print(s.read(4))

# misc control frames
print(ws_read(b"\x89\x00\x81\x04ping", 4))  # FRAME_PING
print(ws_read(b"\x8a\x00\x81\x04pong", 4))  # FRAME_PONG

# close method
ws = websocket.websocket(uio.BytesIO())
ws.close()

# ioctl
ws = websocket.websocket(uio.BytesIO())
print(ws.ioctl(8))  # GET_DATA_OPTS
示例#33
0
def ws_read(msg, sz):
    ws = websocket.websocket(uio.BytesIO(msg))
    return ws.read(sz)
示例#34
0
import websocket
import json

ws = websocket.websocket()

ws.connect("ws://192.168.0.25/")

myDict = {
    "sensor": "temperature",
    "identifier": "SENS123456789",
    "value": 10,
    "timestamp": "20/10/2017 10:10:25"
}

ws.send(json.dumps(myDict))

result = ws.recv()
print(result)

ws.close()