Skip to content

Commit 15de413

Browse files
committed
Made ready for pypi
1 parent b12e115 commit 15de413

13 files changed

+280
-2
lines changed

LICENSE

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
Copyright (c) 2020 Ben Hack
2+
3+
Permission is hereby granted, free of charge, to any person obtaining a copy
4+
of this software and associated documentation files (the "Software"), to deal
5+
in the Software without restriction, including without limitation the rights
6+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7+
copies of the Software, and to permit persons to whom the Software is
8+
furnished to do so, subject to the following conditions:
9+
10+
The above copyright notice and this permission notice shall be included in all
11+
copies or substantial portions of the Software.
12+
13+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19+
SOFTWARE.

README.md

+44-2
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,44 @@
1-
# python-message
2-
A small socket wrapper used in my projects
1+
# python-simpleprotocol
2+
A small socket wrapper
3+
4+
Used for sending code, subcode, parameters.
5+
Code: Integer
6+
Subcode: Integer
7+
Params: Array of strings
8+
9+
10+
Only has basic use, as shown in this example:
11+
12+
13+
Server:
14+
15+
```
16+
17+
import simpleprotocol
18+
19+
server = simpleprotocol.SimpleServer(port=8080)
20+
21+
while True:
22+
handler = server.accept()
23+
handler.send(0)
24+
print(handler.get())
25+
handler.send(1)
26+
print(handler.get())
27+
28+
29+
```
30+
31+
Client:
32+
33+
```
34+
35+
import simpleprotocol
36+
37+
socket = simpleprotocol.SimpleProtocol()
38+
39+
if socket.get().code:
40+
socket.send(1, 0, ["That sounds good!"])
41+
else:
42+
socket.send(1, 1, ["Oh dear, that's not right..."])
43+
44+
```

client.py

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import simpleprotocol
2+
3+
socket = simpleprotocol.SimpleProtocol(port=8080)
4+
5+
if socket.get().code:
6+
socket.send(1, 0, ["That sounds good!"])
7+
else:
8+
socket.send(1, 1, ["Oh dear, that's not right..."])
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

server.py

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import simpleprotocol
2+
3+
server = simpleprotocol.SimpleServer(port=8080)
4+
5+
while True:
6+
handler = server.accept()
7+
handler.send(0)
8+
print(handler.get())
9+
handler = server.accept()
10+
handler.send(1)
11+
print(handler.get())

setup.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import setuptools
2+
3+
with open("README.md", "r") as fh:
4+
long_description = fh.read()
5+
6+
setuptools.setup(
7+
name="simpleprotocol", # Replace with your own username
8+
version="1.0.0",
9+
author="Ben Hack",
10+
author_email="[email protected]",
11+
description="A package for using a basic protocol socket",
12+
long_description=long_description,
13+
long_description_content_type="text/markdown",
14+
url="https://github.com/Chinbob2515/python-message",
15+
packages=setuptools.find_packages(),
16+
classifiers=[
17+
"Programming Language :: Python :: 3",
18+
"License :: OSI Approved :: MIT License",
19+
"Operating System :: OS Independent",
20+
],
21+
python_requires='>=3.6',
22+
)

simpleprotocol/__init__.py

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
from .simpleprotocol import LOG, SimpleServer, SimpleProtocol
2+
3+
__all__ = [
4+
LOG,
5+
SimpleServer,
6+
SimpleProtocol
7+
]

simpleprotocol/message.py

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
2+
class Message():
3+
4+
def __init__(self, socket=None, LOG=False):
5+
self.socket = socket
6+
self.LOG = LOG
7+
8+
def setSocket(self, sock):
9+
self.socket = sock
10+
11+
def encode(self, code, subcode, param):
12+
if type(code) != int:
13+
raise TypeError("Code must be an integer")
14+
if type(subcode) != int:
15+
raise TypeError("Subcode must be an integer")
16+
if type(param) != list:
17+
raise TypeError("Param must be a list")
18+
param = [str(i).replace(":", "\c").replace(";", "\s").replace("\n", "\e") for i in param]
19+
return str(code)+":"+str(subcode)+":"+';'.join(param)
20+
21+
def decode(self, message):
22+
info = {"code": None, "subcode": None, "params": []}
23+
parts = message.split(":")
24+
info["code"] = int(parts[0])
25+
info["subcode"] = int(parts[1])
26+
info["params"] = [i.replace("\c", ":").replace("\s", ";").replace("\e", "\n") for i in parts[2].split(";")]
27+
return Packet(**info)
28+
29+
def get(self):
30+
raw = self.socket.readLine()
31+
if not raw:
32+
return Packet(-1)
33+
result = self.decode(raw)
34+
if self.LOG: print(result)
35+
return result
36+
37+
def send(self, code, subcode=0, param=[]):
38+
self.socket.sendLine(self.encode(code, subcode, param))
39+
40+
41+
# basically a data class, but before 3.7
42+
class Packet:
43+
44+
def __init__(self, code, subcode=0, params=[]):
45+
self.code = code
46+
self.subcode = subcode
47+
self.params = params
48+
49+
def __str__(self):
50+
return f"{self.__class__.__name__}: <code:{self.code}, subcode:{self.subcode}, params:{self.params}>"

simpleprotocol/simpleprotocol.py

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
from . import socketwrapper
2+
from . import message
3+
4+
LOG = False
5+
6+
class SimpleServer():
7+
8+
def __init__(self, port):
9+
self.port = port
10+
self.socket = socketwrapper.ServerSocket(port=port)
11+
12+
def accept(self):
13+
return _SimpleProtocolForServer(self.socket.getClientObject())
14+
15+
class SimpleProtocol():
16+
17+
def __init__(self, port):
18+
self.socket = socketwrapper.ClientSocket(port=port)
19+
self.message = message.Message(socket=self.socket)
20+
21+
def send(self, *args, **kwargs):
22+
return self.message.send(*args, **kwargs)
23+
24+
def get(self, *args, **kwargs):
25+
return self.message.get(*args, **kwargs)
26+
27+
class _SimpleProtocolForServer(SimpleProtocol):
28+
29+
def __init__(self, socket):
30+
self.socket = socket
31+
self.message = message.Message(socket=self.socket)

simpleprotocol/socketwrapper.py

+88
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import socket, sys
2+
3+
ENCODING="UTF-8"
4+
5+
class ServerSocket():
6+
7+
def __init__(self, ip='localhost', port=10000):
8+
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
9+
self.server_address = (ip, port)
10+
self.sock.bind(self.server_address)
11+
self.sock.listen(1)
12+
13+
def accept(self):
14+
connection, client_address = self.sock.accept()
15+
return [connection, client_address]
16+
17+
def getClientObject(self):
18+
return self.ServerSocketHandler(*self.accept())
19+
20+
class ServerSocketHandler():
21+
22+
def __init__(self, connection, client_address):
23+
self.connection = connection
24+
self.client_address = client_address
25+
self.buffer = ""
26+
self.alive = True
27+
28+
def sendLine(self, line):
29+
if not line.endswith("\n"): line += "\n"
30+
self.connection.sendall(line.encode(ENCODING))
31+
32+
def readLine(self):
33+
while not "\n" in self.buffer:
34+
try:
35+
self.buffer += self.connection.recv(64).decode(ENCODING)
36+
except ConnectionResetError:
37+
self.close(response=1)
38+
return None
39+
line = self.buffer.split("\n")[0]
40+
self.buffer = '\n'.join(self.buffer.split("\n")[1:])
41+
self.tryExecOrder(line)
42+
return line
43+
44+
def tryExecOrder(self, line):
45+
if "\k" in line:
46+
self.close(response=1)
47+
48+
def close(self, response=0):
49+
if not response:
50+
self.sendLine("\k")
51+
else:
52+
self.connection.close()
53+
self.alive = False
54+
55+
class ClientSocket():
56+
57+
def __init__(self, ip="localhost", port=10000):
58+
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
59+
self.server_address = (ip, port)
60+
self.sock.connect(self.server_address)
61+
self.buffer = ""
62+
self.alive = True
63+
64+
def sendLine(self, line):
65+
if not line.endswith("\n"): line += "\n"
66+
self.sock.sendall(line.encode(ENCODING))
67+
68+
def readLine(self):
69+
while not "\n" in self.buffer:
70+
try:
71+
self.buffer += self.sock.recv(64).decode(ENCODING)
72+
except ConnectionResetError:
73+
self.close(response=1)
74+
return None
75+
line = self.buffer.split("\n")[0]
76+
self.buffer = '\n'.join(self.buffer.split("\n")[1:])
77+
self.tryExecOrder(line)
78+
return line
79+
80+
def tryExecOrder(self, line):
81+
if "\k" in line:
82+
self.close()
83+
84+
def close(self):
85+
self.sendLine("\k")
86+
self.sock.close()
87+
self.alive = False
88+

0 commit comments

Comments
 (0)