Skip to content

Instantly share code, notes, and snippets.

@EteimZ
Last active December 15, 2022 09:14
Show Gist options
  • Select an option

  • Save EteimZ/a9973fb310a96476bfd9bdb986b96b4f to your computer and use it in GitHub Desktop.

Select an option

Save EteimZ/a9973fb310a96476bfd9bdb986b96b4f to your computer and use it in GitHub Desktop.
Simple example of using websocket with vue.
import asyncio
import datetime
import random
import websockets
"""
Server implementation with broadcast functionality
"""
#websocket connections
CONNECTIONS = set()
async def register(websocket):
"""
Register new connections
"""
CONNECTIONS.add(websocket)
try:
# await for connection to close
await websocket.wait_closed()
finally:
# Then remove connection from set
CONNECTIONS.remove(websocket)
async def show_time():
while True:
message = datetime.datetime.utcnow().isoformat() + "Z"
# broadcast message to all connections
websockets.broadcast(CONNECTIONS, message)
await asyncio.sleep(random.random() * 2 + 1)
async def main():
async with websockets.serve(register, "localhost", 5678):
await show_time()
if __name__ == "__main__":
print("Server running via localhost on port 5678")
asyncio.run(main())
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<title>Vue-websockets</title>
</head>
<body>
<div id="app">
<ul>
<li v-for="msg in message">{{msg}}</li>
</ul>
</div>
</body>
<script src="index.js"></script>
</html>
const { createApp } = Vue
createApp({
data() {
return {
message: []
}
},
created(){
const websocket = new WebSocket("ws://localhost:5678/");
websocket.onmessage = ({data}) => {
this.message.push(data);
}
}
}).mount('#app')
import asyncio
import datetime
import random
import websockets
"""
Server implementation in python
"""
async def show_time(websocket):
while True:
message = datetime.datetime.utcnow().isoformat() + "Z"
await websocket.send(message)
await asyncio.sleep(random.random() * 2 + 1)
async def main():
async with websockets.serve(show_time, "localhost", 5678):
await asyncio.Future() # run forever
if __name__ == "__main__":
print("Server running via localhost on port 5678")
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment