Skip to content

Commit 18756d5

Browse files
bluetechpgjones
authored andcommitted
Reformat example with Black
To be consistent with the rest of the project. Also checked in CI.
1 parent afe01c4 commit 18756d5

File tree

3 files changed

+66
-49
lines changed

3 files changed

+66
-49
lines changed

example/synchronous_client.py

Lines changed: 33 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,44 @@
1-
'''
1+
"""
22
The client reads a line from stdin, sends it to the server, then prints the
33
response. This is a poor implementation of a client. It is only intended to
44
demonstrate how to use wsproto.
5-
'''
5+
"""
66

77
import socket
88
import sys
99

1010
from wsproto import WSConnection
1111
from wsproto.connection import ConnectionType
12-
from wsproto.events import AcceptConnection, CloseConnection, Message, Ping, Pong, Request, TextMessage
13-
12+
from wsproto.events import (
13+
AcceptConnection,
14+
CloseConnection,
15+
Message,
16+
Ping,
17+
Pong,
18+
Request,
19+
TextMessage,
20+
)
1421

1522
RECEIVE_BYTES = 4096
1623

1724

1825
def main():
19-
''' Run the client. '''
26+
"""Run the client."""
2027
try:
2128
host = sys.argv[1]
2229
port = int(sys.argv[2])
2330
except (IndexError, ValueError):
24-
print('Usage: {} <HOST> <PORT>'.format(sys.argv[0]))
31+
print("Usage: {} <HOST> <PORT>".format(sys.argv[0]))
2532
sys.exit(1)
2633

2734
try:
2835
wsproto_demo(host, port)
2936
except KeyboardInterrupt:
30-
print('\nReceived SIGINT: shutting down…')
37+
print("\nReceived SIGINT: shutting down…")
3138

3239

3340
def wsproto_demo(host, port):
34-
'''
41+
"""
3542
Demonstrate wsproto:
3643
3744
0) Open TCP connection
@@ -41,39 +48,39 @@ def wsproto_demo(host, port):
4148
4) Negotiate WebSocket closing handshake
4249
4350
:param stream: a socket stream
44-
'''
51+
"""
4552

4653
# 0) Open TCP connection
47-
print('Connecting to {}:{}'.format(host, port))
54+
print("Connecting to {}:{}".format(host, port))
4855
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
4956
conn.connect((host, port))
5057

5158
# 1) Negotiate WebSocket opening handshake
52-
print('Opening WebSocket')
59+
print("Opening WebSocket")
5360
ws = WSConnection(ConnectionType.CLIENT)
5461
# Because this is a client WebSocket, we need to initiate the connection
5562
# handshake by sending a Request event.
56-
net_send(ws.send(Request(host=host, target='server')), conn)
63+
net_send(ws.send(Request(host=host, target="server")), conn)
5764
net_recv(ws, conn)
5865
handle_events(ws)
5966

6067
# 2) Send a message and display response
6168
message = "wsproto is great"
62-
print('Sending message: {}'.format(message))
69+
print("Sending message: {}".format(message))
6370
net_send(ws.send(Message(data=message)), conn)
6471
net_recv(ws, conn)
6572
handle_events(ws)
6673

6774
# 3) Send ping and display pong
6875
payload = b"table tennis"
69-
print('Sending ping: {}'.format(payload))
76+
print("Sending ping: {}".format(payload))
7077
net_send(ws.send(Ping(payload=payload)), conn)
7178
net_recv(ws, conn)
7279
handle_events(ws)
7380

7481
# 4) Negotiate WebSocket closing handshake
75-
print('Closing WebSocket')
76-
net_send(ws.send(CloseConnection(code=1000, reason='sample reason')), conn)
82+
print("Closing WebSocket")
83+
net_send(ws.send(CloseConnection(code=1000, reason="sample reason")), conn)
7784
# After sending the closing frame, we won't get any more events. The server
7885
# should send a reply and then close the connection, so we need to receive
7986
# twice:
@@ -83,35 +90,35 @@ def wsproto_demo(host, port):
8390

8491

8592
def net_send(out_data, conn):
86-
''' Write pending data from websocket to network. '''
87-
print('Sending {} bytes'.format(len(out_data)))
93+
""" Write pending data from websocket to network. """
94+
print("Sending {} bytes".format(len(out_data)))
8895
conn.send(out_data)
8996

9097

9198
def net_recv(ws, conn):
92-
''' Read pending data from network into websocket. '''
99+
""" Read pending data from network into websocket. """
93100
in_data = conn.recv(RECEIVE_BYTES)
94101
if not in_data:
95102
# A receive of zero bytes indicates the TCP socket has been closed. We
96103
# need to pass None to wsproto to update its internal state.
97-
print('Received 0 bytes (connection closed)')
104+
print("Received 0 bytes (connection closed)")
98105
ws.receive_data(None)
99106
else:
100-
print('Received {} bytes'.format(len(in_data)))
107+
print("Received {} bytes".format(len(in_data)))
101108
ws.receive_data(in_data)
102109

103110

104111
def handle_events(ws):
105112
for event in ws.events():
106113
if isinstance(event, AcceptConnection):
107-
print('WebSocket negotiation complete')
114+
print("WebSocket negotiation complete")
108115
elif isinstance(event, TextMessage):
109-
print('Received message: {}'.format(event.data))
116+
print("Received message: {}".format(event.data))
110117
elif isinstance(event, Pong):
111-
print('Received pong: {}'.format(event.payload))
118+
print("Received pong: {}".format(event.payload))
112119
else:
113-
raise Exception('Do not know how to handle event: ' + str(event))
120+
raise Exception("Do not know how to handle event: " + str(event))
114121

115122

116-
if __name__ == '__main__':
123+
if __name__ == "__main__":
117124
main()

example/synchronous_server.py

Lines changed: 31 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,34 @@
1-
'''
1+
"""
22
This server reads a message from a WebSocket, and sends the reverse string in a
33
response message. It can only handle one client at a time. This is a very bad
44
implementation of a server! It is only intended to demonstrate how to use
55
wsproto.
6-
'''
6+
"""
77

88
import socket
99
import sys
1010

1111
from wsproto import ConnectionType, WSConnection
12-
from wsproto.events import AcceptConnection, CloseConnection, Message, Ping, Request, TextMessage
13-
12+
from wsproto.events import (
13+
AcceptConnection,
14+
CloseConnection,
15+
Message,
16+
Ping,
17+
Request,
18+
TextMessage,
19+
)
1420

1521
MAX_CONNECTS = 5
1622
RECEIVE_BYTES = 4096
1723

24+
1825
def main():
19-
''' Run the server. '''
26+
"""Run the server."""
2027
try:
2128
ip = sys.argv[1]
2229
port = int(sys.argv[2])
2330
except (IndexError, ValueError):
24-
print('Usage: {} <BIND_IP> <PORT>'.format(sys.argv[0]))
31+
print("Usage: {} <BIND_IP> <PORT>".format(sys.argv[0]))
2532
sys.exit(1)
2633

2734
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
@@ -31,18 +38,18 @@ def main():
3138

3239
try:
3340
while True:
34-
print('Waiting for connection...')
41+
print("Waiting for connection...")
3542
(stream, addr) = server.accept()
36-
print('Client connected: {}:{}'.format(addr[0], addr[1]))
43+
print("Client connected: {}:{}".format(addr[0], addr[1]))
3744
handle_connection(stream)
3845
stream.shutdown(socket.SHUT_WR)
3946
stream.close()
4047
except KeyboardInterrupt:
41-
print('Received SIGINT: shutting down…')
48+
print("Received SIGINT: shutting down…")
4249

4350

4451
def handle_connection(stream):
45-
'''
52+
"""
4653
Handle a connection.
4754
4855
The server operates a request/response cycle, so it performs a synchronous
@@ -53,46 +60,49 @@ def handle_connection(stream):
5360
3) Send data from wsproto to network
5461
5562
:param stream: a socket stream
56-
'''
63+
"""
5764
ws = WSConnection(ConnectionType.SERVER)
5865
running = True
5966

6067
while running:
6168
# 1) Read data from network
6269
in_data = stream.recv(RECEIVE_BYTES)
63-
print('Received {} bytes'.format(len(in_data)))
70+
print("Received {} bytes".format(len(in_data)))
6471
ws.receive_data(in_data)
6572

6673
# 2) Get new events and handle them
67-
out_data = b''
74+
out_data = b""
6875
for event in ws.events():
6976
if isinstance(event, Request):
7077
# Negotiate new WebSocket connection
71-
print('Accepting WebSocket upgrade')
78+
print("Accepting WebSocket upgrade")
7279
out_data += ws.send(AcceptConnection())
7380
elif isinstance(event, CloseConnection):
7481
# Print log message and break out
75-
print('Connection closed: code={}/{} reason={}'.format(
76-
event.code.value, event.code.name, event.reason))
82+
print(
83+
"Connection closed: code={}/{} reason={}".format(
84+
event.code.value, event.code.name, event.reason
85+
)
86+
)
7787
out_data += ws.send(event.response())
7888
running = False
7989
elif isinstance(event, TextMessage):
8090
# Reverse text and send it back to wsproto
81-
print('Received request and sending response')
91+
print("Received request and sending response")
8292
out_data += ws.send(Message(data=event.data[::-1]))
8393
elif isinstance(event, Ping):
8494
# wsproto handles ping events for you by placing a pong frame in
8595
# the outgoing buffer. You should not call pong() unless you want to
8696
# send an unsolicited pong frame.
87-
print('Received ping and sending pong')
97+
print("Received ping and sending pong")
8898
out_data += ws.send(event.response())
8999
else:
90-
print('Unknown event: {!r}'.format(event))
100+
print("Unknown event: {!r}".format(event))
91101

92102
# 4) Send data from wsproto to network
93-
print('Sending {} bytes'.format(len(out_data)))
103+
print("Sending {} bytes".format(len(out_data)))
94104
stream.send(out_data)
95105

96106

97-
if __name__ == '__main__':
107+
if __name__ == "__main__":
98108
main()

tox.ini

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,8 @@ deps =
2929
black
3030
isort
3131
commands =
32-
black --check --diff wsproto/ test/
33-
isort --dont-skip __init__.py --diff --check --settings-path setup.cfg --recursive wsproto test
32+
black --check --diff wsproto/ test/ example/
33+
isort --dont-skip __init__.py --diff --check --settings-path setup.cfg --recursive wsproto test example
3434

3535
[testenv:mypy]
3636
basepython = python3.7

0 commit comments

Comments
 (0)