Where to Discuss?

Local Group


Goal: Monitor excel file changes and show the result in browser using websocket.

This is a multiparts article.

5: Sending and Receiving

Await Asynchronously

Python Source Code

We have to source code here. The sender and the receiver.

Class Skeleton


The definition is identical with previous code.

class Xl2WebExample:
  def __init__(self, filepath, filename, site, port):
  async def handler(self, websocket, path):
  async def main(self):

Python: Sending and Receiving: Brief

Only the implementation detail of the the handler that are different.

Class: Websocket Handler


Here we only monitor a particular file, such as /home/epsi/awatchtest-a.xlsx.

  async def handler(self, websocket, path):
    async for changes in awatch(self.filepath):
      xlsx = self.filepath + '/' + self.filename

      for change in changes:
        if change[1] == xlsx:
          await websocket.send(change[1])

Python: Sending and Receiving: Handler

The os library is smart enough to differ between slash in linux, or backslash in windows.

      self.xlsx = os.path.join(self.filepath, self.filename)

CLI Client Side


This will consumed data sent by the producer.

import asyncio
import websockets

async def push_client():
  async with websockets.\
    connect("ws://localhost:8765") as websocket:
    while True:
      data = await websocket.recv()
      print("Received data:", data)

loop = asyncio.new_event_loop()

All we need to know is the websocket connection.

  async with websockets.\
    connect("ws://localhost:8765") a    self.websocket = websockets websocket:

Output in CLI

Open both, script and python websocket.

Sender in CLI

❯ python 14-send.py

Receiver in CLI

❯ python 14-recv.py
Received data: /home/epsi/awatch/test-a.xlsx

Python: Sending and Receiving: Receive

Note that if we close connection from the sender, the receiver will deliver this error messages.

Python: Sending and Receiving: Closed

You can disable the trace back message on Ctrl+c event, by catching the exception handler.

except KeyboardInterrupt:

Web Source Code

Client Side

We can settle an element to be for value holder.

    <h1>Your mission. Good Luck!</h1>
    <div id="output"></div>

And we can retrieve the data using websocket

  "DOMContentLoaded", function(event) {
     const websocket = new WebSocket("ws://localhost:8765");
     const output = document.getElementById("output");

     websocket.onmessage = function(event) {
       const data = event.data; 
       output.innerHTML += `<p>Received: ${data}</p>`;

Site: Sending and Receiving: HTML

Browser Result

Consider examine the result in browser.

Site: Sending and Receiving: Display: Message

Simple right! This should also works in your computer.

What is Next 🤔?

We are done with sending and receiving. We should be ready ot read our excel file, and send the data.

Consider continue reading [ Excel - Monitor - Reading Worksheet ].