1import socketio
2
3sio = socketio.AsyncServer()
4app = web.Application()
5sio.attach(app)
6
7async def index(request):
8 """Serve the client-side application."""
9 with open('index.html') as f:
10 return web.Response(text=f.read(), content_type='text/html')
11
12@sio.event
13def connect(sid, environ):
14 print("connect ", sid)
15
16@sio.event
17async def chat_message(sid, data):
18 print("message ", data)
19 await sio.emit('reply', room=sid)
20
21@sio.event
22def disconnect(sid):
23 print('disconnect ', sid)
24
25app.router.add_static('/static', 'static')
26app.router.add_get('/', index)
27
28if __name__ == '__main__':
29 web.run_app(app)
1import socket
2
3HOST = '127.0.0.1' # Standard loopback interface address (localhost)
4PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
5
6with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
7 s.bind((HOST, PORT))
8 s.listen()
9 conn, addr = s.accept()
10 with conn:
11 print('Connected by', addr)
12 while True:
13 data = conn.recv(1024)
14 if not data:
15 break
16 conn.sendall(data)
1<script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js" integrity="sha256-yr4fRk/GU1ehYJPAs8P4JlTgu0Hdsp4ZKrx8bDEDC3I=" crossorigin="anonymous"></script>
2<script type="text/javascript" charset="utf-8">
3 var socket = io();
4 socket.on('connect', function() {
5 socket.emit('my event', {data: 'I\'m connected!'});
6 });
7</script>
8