Skip to content

Instantly share code, notes, and snippets.

@habnabit
Last active June 30, 2016 17:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save habnabit/181472fcca0fe75b3cd4bc55b98a8731 to your computer and use it in GitHub Desktop.
Save habnabit/181472fcca0fe75b3cd4bc55b98a8731 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>WebSocket demo</title>
</head>
<body>
<form id="chatform">
<input type="text" id="line" autocomplete="off">
</form>
<script>
var ws = new WebSocket("ws://127.0.0.1:8765/"),
messages = document.createElement('ul');
ws.onmessage = function (event) {
var messages = document.getElementsByTagName('ul')[0],
message = document.createElement('li'),
content = document.createTextNode(event.data);
message.appendChild(content);
messages.appendChild(message);
};
document.body.appendChild(messages);
document.getElementById('chatform').onsubmit = function () {
var line = this.line.value;
this.line.value = '';
ws.send(line);
return false;
};
</script>
</body>
</html>
Copyright 2016 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
import asyncio
import contextlib
import datetime
import websockets
class SocketCollector(object):
def __init__(self):
self.sockets = set()
def add(self, sock):
@contextlib.contextmanager
def c():
self.sockets.add(sock)
try:
yield self
finally:
self.sockets.discard(sock)
return c()
def __iter__(self):
return iter(list(self.sockets))
class ChatServer(object):
def __init__(self):
self.sockets = SocketCollector()
async def serve(self, websocket, path):
with self.sockets.add(websocket) as everyone:
while True:
message = await websocket.recv()
message = '[{:%H:%M:%S}] {}'.format(datetime.datetime.now(), message)
for other in everyone:
await other.send(message)
async def notify_all_periodically(self):
while True:
message = 'The time is: {:%H:%M:%S}'.format(datetime.datetime.now())
for socket in self.sockets:
await socket.send(message)
await asyncio.sleep(10)
loop = asyncio.get_event_loop()
chat = ChatServer()
start_server = websockets.serve(chat.serve, 'localhost', 8765)
loop.create_task(chat.notify_all_periodically())
loop.run_until_complete(start_server)
loop.run_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment