-
Notifications
You must be signed in to change notification settings - Fork 34
pep8 and python3 compat #3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
cybermerc
wants to merge
1
commit into
mdebbar:master
Choose a base branch
from
cybermerc:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,134 +1,136 @@ | ||
import json, socket | ||
#!/usr/bin/env python | ||
|
||
import json | ||
import socket | ||
|
||
|
||
class Server(object): | ||
""" | ||
A JSON socket server used to communicate with a JSON socket client. All the | ||
data is serialized in JSON. How to use it: | ||
server = Server(host, port) | ||
while True: | ||
server.accept() | ||
data = server.recv() | ||
# shortcut: data = server.accept().recv() | ||
server.send({'status': 'ok'}) | ||
""" | ||
|
||
backlog = 5 | ||
client = None | ||
|
||
def __init__(self, host, port): | ||
self.socket = socket.socket() | ||
self.socket.bind((host, port)) | ||
self.socket.listen(self.backlog) | ||
|
||
def __del__(self): | ||
self.close() | ||
|
||
def accept(self): | ||
# if a client is already connected, disconnect it | ||
if self.client: | ||
self.client.close() | ||
self.client, self.client_addr = self.socket.accept() | ||
return self | ||
|
||
def send(self, data): | ||
if not self.client: | ||
raise Exception('Cannot send data, no client is connected') | ||
_send(self.client, data) | ||
return self | ||
|
||
def recv(self): | ||
if not self.client: | ||
raise Exception('Cannot receive data, no client is connected') | ||
return _recv(self.client) | ||
|
||
def close(self): | ||
if self.client: | ||
self.client.close() | ||
self.client = None | ||
if self.socket: | ||
self.socket.close() | ||
self.socket = None | ||
""" | ||
A JSON socket server used to communicate with a JSON socket client. All the | ||
data is serialized in JSON. How to use it: | ||
server = Server(host, port) | ||
while True: | ||
server.accept() | ||
data = server.recv() | ||
# shortcut: data = server.accept().recv() | ||
server.send({'status': 'ok'}) | ||
""" | ||
|
||
backlog = 5 | ||
client = None | ||
|
||
def __init__(self, host, port): | ||
self.socket = socket.socket() | ||
self.socket.bind((host, port)) | ||
self.socket.listen(self.backlog) | ||
|
||
def __del__(self): | ||
self.close() | ||
|
||
def accept(self): | ||
# if a client is already connected, disconnect it | ||
if self.client: | ||
self.client.close() | ||
self.client, self.client_addr = self.socket.accept() | ||
return self | ||
|
||
def send(self, data): | ||
if not self.client: | ||
raise Exception('Cannot send data, no client is connected') | ||
_send(self.client, data) | ||
return self | ||
|
||
def recv(self): | ||
if not self.client: | ||
raise Exception('Cannot receive data, no client is connected') | ||
return _recv(self.client) | ||
|
||
def close(self): | ||
if self.client: | ||
self.client.close() | ||
self.client = None | ||
if self.socket: | ||
self.socket.close() | ||
self.socket = None | ||
|
||
|
||
class Client(object): | ||
""" | ||
A JSON socket client used to communicate with a JSON socket server. All the | ||
data is serialized in JSON. How to use it: | ||
data = { | ||
'name': 'Patrick Jane', | ||
'age': 45, | ||
'children': ['Susie', 'Mike', 'Philip'] | ||
} | ||
client = Client() | ||
client.connect(host, port) | ||
client.send(data) | ||
response = client.recv() | ||
# or in one line: | ||
response = Client().connect(host, port).send(data).recv() | ||
""" | ||
|
||
socket = None | ||
|
||
def __del__(self): | ||
self.close() | ||
|
||
def connect(self, host, port): | ||
self.socket = socket.socket() | ||
self.socket.connect((host, port)) | ||
return self | ||
|
||
def send(self, data): | ||
if not self.socket: | ||
raise Exception('You have to connect first before sending data') | ||
_send(self.socket, data) | ||
return self | ||
|
||
def recv(self): | ||
if not self.socket: | ||
raise Exception('You have to connect first before receiving data') | ||
return _recv(self.socket) | ||
|
||
def recv_and_close(self): | ||
data = self.recv() | ||
self.close() | ||
return data | ||
|
||
def close(self): | ||
if self.socket: | ||
self.socket.close() | ||
self.socket = None | ||
|
||
|
||
## helper functions ## | ||
|
||
""" | ||
A JSON socket client used to communicate with a JSON socket server. All the | ||
data is serialized in JSON. How to use it: | ||
data = { | ||
'name': 'Patrick Jane', | ||
'age': 45, | ||
'children': ['Susie', 'Mike', 'Philip'] | ||
} | ||
client = Client() | ||
client.connect(host, port) | ||
client.send(data) | ||
response = client.recv() | ||
# or in one line: | ||
response = Client().connect(host, port).send(data).recv() | ||
""" | ||
|
||
socket = None | ||
|
||
def __del__(self): | ||
self.close() | ||
|
||
def connect(self, host, port): | ||
self.socket = socket.socket() | ||
self.socket.connect((host, port)) | ||
return self | ||
|
||
def send(self, data): | ||
if not self.socket: | ||
raise Exception('You have to connect first before sending data') | ||
_send(self.socket, data) | ||
return self | ||
|
||
def recv(self): | ||
if not self.socket: | ||
raise Exception('You have to connect first before receiving data') | ||
return _recv(self.socket) | ||
|
||
def recv_and_close(self): | ||
data = self.recv() | ||
self.close() | ||
return data | ||
|
||
def close(self): | ||
if self.socket: | ||
self.socket.close() | ||
self.socket = None | ||
|
||
|
||
# helper functions | ||
def _send(socket, data): | ||
try: | ||
serialized = json.dumps(data) | ||
except (TypeError, ValueError), e: | ||
raise Exception('You can only send JSON-serializable data') | ||
# send the length of the serialized data first | ||
socket.send('%d\n' % len(serialized)) | ||
# send the serialized data | ||
socket.sendall(serialized) | ||
try: | ||
serialized = json.dumps(data) | ||
except (TypeError, ValueError) as e: | ||
raise Exception('You can only send JSON-serializable data') | ||
# send the length of the serialized data first | ||
socket.send('{}\n'.format(len(serialized)).encode('utf-8')) | ||
# send the serialized data | ||
socket.sendall(serialized.encode('utf-8')) | ||
|
||
|
||
def _recv(socket): | ||
# read the length of the data, letter by letter until we reach EOL | ||
length_str = '' | ||
char = socket.recv(1) | ||
while char != '\n': | ||
length_str += char | ||
char = socket.recv(1) | ||
total = int(length_str) | ||
# use a memoryview to receive the data chunk by chunk efficiently | ||
view = memoryview(bytearray(total)) | ||
next_offset = 0 | ||
while total - next_offset > 0: | ||
recv_size = socket.recv_into(view[next_offset:], total - next_offset) | ||
next_offset += recv_size | ||
try: | ||
deserialized = json.loads(view.tobytes()) | ||
except (TypeError, ValueError), e: | ||
raise Exception('Data received was not in JSON format') | ||
return deserialized | ||
# read the length of the data, letter by letter until we reach EOL | ||
length_str = '' | ||
char = socket.recv(1).decode('utf-8') | ||
while char != '\n': | ||
length_str += char | ||
char = socket.recv(1).decode('utf-8') | ||
total = int(length_str) | ||
# use a memoryview to receive the data chunk by chunk efficiently | ||
view = memoryview(bytearray(total)) | ||
next_offset = 0 | ||
while total - next_offset > 0: | ||
recv_size = socket.recv_into(view[next_offset:], total - next_offset) | ||
next_offset += recv_size | ||
try: | ||
deserialized = json.loads(view.tobytes().decode()) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should this be |
||
except (TypeError, ValueError) as e: | ||
raise Exception('Data received was not in JSON format') | ||
return deserialized |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think you should encode the data here so that we get the correct length below.