jsocket 1.9.5__py3-none-any.whl → 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
jsocket/__init__.py CHANGED
@@ -73,3 +73,4 @@
73
73
  """
74
74
  from jsocket.jsocket_base import *
75
75
  from jsocket.tserver import *
76
+ from ._version import __version__
jsocket/_version.py ADDED
@@ -0,0 +1,3 @@
1
+ """Package version."""
2
+
3
+ __version__ = "2.0.0"
jsocket/jsocket_base.py CHANGED
@@ -19,16 +19,26 @@ __copyright__= """
19
19
  See the License for the specific language governing permissions and
20
20
  limitations under the License.
21
21
  """
22
- __version__ = "1.0.3"
23
-
24
22
  import json
25
23
  import socket
26
24
  import struct
27
25
  import logging
28
26
  import time
27
+ import zlib
28
+
29
+ from ._version import __version__
29
30
 
30
31
  logger = logging.getLogger("jsocket")
31
32
 
33
+ FRAME_MAGIC = b"JSN1"
34
+ FRAME_HEADER_FMT = "!4sII"
35
+ FRAME_HEADER_SIZE = struct.calcsize(FRAME_HEADER_FMT)
36
+ DEFAULT_MAX_MESSAGE_SIZE = 10 * 1024 * 1024
37
+
38
+
39
+ class FramingError(RuntimeError):
40
+ """Raised when a message fails framing or integrity checks."""
41
+
32
42
 
33
43
  def _socket_fileno(sock):
34
44
  try:
@@ -40,12 +50,15 @@ def _socket_fileno(sock):
40
50
  class JsonSocket:
41
51
  """Lightweight JSON-over-TCP socket wrapper with length-prefixed framing."""
42
52
 
43
- def __init__(self, address='127.0.0.1', port=5489, timeout=2.0):
53
+ def __init__(self, address='127.0.0.1', port=5489, timeout=2.0, max_message_size=DEFAULT_MAX_MESSAGE_SIZE):
44
54
  self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
45
55
  self.conn = self.socket
46
56
  self._timeout = timeout
47
57
  self._address = address
48
58
  self._port = port
59
+ self._max_message_size = None
60
+ self.max_message_size = max_message_size
61
+ self._last_client_addr = None
49
62
  # Ensure the primary socket respects timeout for accept/connect operations
50
63
  self.socket.settimeout(self._timeout)
51
64
 
@@ -54,11 +67,12 @@ class JsonSocket:
54
67
  msg = json.dumps(obj, ensure_ascii=False)
55
68
  if self.socket:
56
69
  payload = msg.encode('utf-8')
57
- frmt = f"={len(payload)}s"
58
- packed_msg = struct.pack(frmt, payload)
59
- packed_hdr = struct.pack('!I', len(packed_msg))
70
+ if self._max_message_size is not None and len(payload) > self._max_message_size:
71
+ raise ValueError(f"message exceeds max_message_size ({len(payload)} > {self._max_message_size})")
72
+ checksum = zlib.crc32(payload) & 0xFFFFFFFF
73
+ packed_hdr = struct.pack(FRAME_HEADER_FMT, FRAME_MAGIC, len(payload), checksum)
60
74
  self._send(packed_hdr)
61
- self._send(packed_msg)
75
+ self._send(payload)
62
76
 
63
77
  def _send(self, msg):
64
78
  """Send all bytes in `msg` to the peer."""
@@ -66,29 +80,53 @@ class JsonSocket:
66
80
  while sent < len(msg):
67
81
  sent += self.conn.send(msg[sent:])
68
82
 
69
- def _read(self, size):
83
+ def _read(self, size, allow_timeout=False):
70
84
  """Read exactly `size` bytes from the peer or raise on disconnect."""
71
85
  data = b''
72
86
  while len(data) < size:
73
- data_tmp = self.conn.recv(size - len(data))
74
- data += data_tmp
87
+ try:
88
+ data_tmp = self.conn.recv(size - len(data))
89
+ except socket.timeout:
90
+ if allow_timeout and not data:
91
+ raise
92
+ self._close_connection()
93
+ raise FramingError("socket read timeout during message")
75
94
  if data_tmp == b'':
95
+ self._close_connection()
76
96
  raise RuntimeError("socket connection broken")
97
+ data += data_tmp
77
98
  return data
78
99
 
79
- def _msg_length(self):
80
- """Read and unpack the 4-byte big-endian length header."""
81
- d = self._read(4)
82
- s = struct.unpack('!I', d)
83
- return s[0]
100
+ def _read_header(self):
101
+ """Read and unpack the framing header."""
102
+ header = self._read(FRAME_HEADER_SIZE, allow_timeout=True)
103
+ magic, size, checksum = struct.unpack(FRAME_HEADER_FMT, header)
104
+ if magic != FRAME_MAGIC:
105
+ self._close_connection()
106
+ raise FramingError("invalid message header magic")
107
+ if self._max_message_size is not None and size > self._max_message_size:
108
+ self._close_connection()
109
+ raise FramingError(f"message length {size} exceeds max_message_size {self._max_message_size}")
110
+ return size, checksum
84
111
 
85
112
  def read_obj(self):
86
113
  """Read a full message and decode it as JSON, returning a Python object."""
87
- size = self._msg_length()
114
+ size, checksum = self._read_header()
88
115
  data = self._read(size)
89
- frmt = f"={size}s"
90
- msg = struct.unpack(frmt, data)
91
- return json.loads(msg[0].decode('utf-8'))
116
+ actual = zlib.crc32(data) & 0xFFFFFFFF
117
+ if actual != checksum:
118
+ self._close_connection()
119
+ raise FramingError("message checksum mismatch")
120
+ try:
121
+ decoded = data.decode('utf-8')
122
+ except UnicodeDecodeError as e:
123
+ self._close_connection()
124
+ raise FramingError("invalid UTF-8 payload") from e
125
+ try:
126
+ return json.loads(decoded)
127
+ except json.JSONDecodeError as e:
128
+ self._close_connection()
129
+ raise FramingError("invalid JSON payload") from e
92
130
 
93
131
  def close(self):
94
132
  """Close active connection and the listening socket if open."""
@@ -117,10 +155,10 @@ class JsonSocket:
117
155
  pass
118
156
 
119
157
  def _close_connection(self):
120
- """Best-effort shutdown and close of the accepted connection socket."""
158
+ """Best-effort shutdown and close of the connection socket."""
121
159
  logger.debug("closing connection socket (fd=%s)", _socket_fileno(self.conn))
122
160
  try:
123
- if self.conn and self.conn is not self.socket and self.conn.fileno() != -1:
161
+ if self.conn and self.conn.fileno() != -1:
124
162
  try:
125
163
  self.conn.shutdown(socket.SHUT_RDWR)
126
164
  except OSError:
@@ -157,9 +195,24 @@ class JsonSocket:
157
195
  """No-op: port is read-only after initialization."""
158
196
  return None
159
197
 
198
+ def _get_max_message_size(self):
199
+ """Get the maximum allowed message size in bytes."""
200
+ return self._max_message_size
201
+
202
+ def _set_max_message_size(self, size):
203
+ """Set the maximum allowed message size in bytes."""
204
+ if size is None:
205
+ self._max_message_size = None
206
+ return
207
+ size = int(size)
208
+ if size <= 0:
209
+ raise ValueError("max_message_size must be positive")
210
+ self._max_message_size = size
211
+
160
212
  timeout = property(_get_timeout, _set_timeout, doc='Get/set the socket timeout')
161
213
  address = property(_get_address, _set_address, doc='read only property socket address')
162
214
  port = property(_get_port, _set_port, doc='read only property socket port')
215
+ max_message_size = property(_get_max_message_size, _set_max_message_size, doc='Get/set max message size in bytes')
163
216
 
164
217
 
165
218
  class JsonServer(JsonSocket):
@@ -169,6 +222,22 @@ class JsonServer(JsonSocket):
169
222
  super().__init__(address, port)
170
223
  self._bind()
171
224
 
225
+ def _close_connection(self):
226
+ """Best-effort shutdown and close of the accepted connection socket."""
227
+ logger.debug("closing connection socket (fd=%s)", _socket_fileno(self.conn))
228
+ try:
229
+ if self.conn and self.conn is not self.socket and self.conn.fileno() != -1:
230
+ try:
231
+ self.conn.shutdown(socket.SHUT_RDWR)
232
+ except OSError:
233
+ pass
234
+ try:
235
+ self.conn.close()
236
+ except OSError:
237
+ pass
238
+ except OSError:
239
+ pass
240
+
172
241
  def _bind(self):
173
242
  self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
174
243
  self.socket.bind((self.address, self.port))
@@ -183,6 +252,7 @@ class JsonServer(JsonSocket):
183
252
  """Listen and accept a single client connection; set timeout accordingly."""
184
253
  self._listen()
185
254
  self.conn, addr = self._accept()
255
+ self._last_client_addr = addr
186
256
  self.conn.settimeout(self.timeout)
187
257
  logger.debug(
188
258
  "connection accepted, conn socket (%s,%d,%s)", addr[0], addr[1], str(self.conn.gettimeout())
jsocket/tserver.py CHANGED
@@ -20,15 +20,15 @@ __copyright__= """
20
20
  See the License for the specific language governing permissions and
21
21
  limitations under the License.
22
22
  """
23
- __version__ = "1.0.3"
24
-
25
23
  import threading
26
24
  import socket
27
25
  import time
28
26
  import logging
29
27
  import abc
30
28
  from typing import Optional
29
+
31
30
  from jsocket import jsocket_base
31
+ from ._version import __version__
32
32
 
33
33
  logger = logging.getLogger("jsocket.tserver")
34
34
 
@@ -41,6 +41,16 @@ def _response_summary(resp_obj) -> str:
41
41
  return f"type={type(resp_obj).__name__}"
42
42
 
43
43
 
44
+ def _format_client_id(addr) -> str:
45
+ try:
46
+ host, port = addr[0], addr[1]
47
+ if ":" in host:
48
+ return f"[{host}]:{port}"
49
+ return f"{host}:{port}"
50
+ except Exception: # pylint: disable=broad-exception-caught
51
+ return "unknown"
52
+
53
+
44
54
  class ThreadedServer(threading.Thread, jsocket_base.JsonServer, metaclass=abc.ABCMeta):
45
55
  """Single-threaded server that accepts one connection and processes messages in its thread."""
46
56
 
@@ -48,6 +58,9 @@ class ThreadedServer(threading.Thread, jsocket_base.JsonServer, metaclass=abc.AB
48
58
  threading.Thread.__init__(self)
49
59
  jsocket_base.JsonServer.__init__(self, **kwargs)
50
60
  self._is_alive = False
61
+ self._stats_lock = threading.Lock()
62
+ self._client_started_at = None
63
+ self._client_id = None
51
64
 
52
65
  @abc.abstractmethod
53
66
  def _process_message(self, obj) -> Optional[dict]:
@@ -61,6 +74,32 @@ class ThreadedServer(threading.Thread, jsocket_base.JsonServer, metaclass=abc.AB
61
74
  # Return None in the base class to satisfy linters; subclasses should override.
62
75
  return None
63
76
 
77
+ def _record_client_start(self):
78
+ addr = getattr(self, "_last_client_addr", None)
79
+ if addr is None:
80
+ try:
81
+ addr = self.conn.getpeername()
82
+ except OSError:
83
+ addr = None
84
+ with self._stats_lock:
85
+ self._client_started_at = time.monotonic()
86
+ self._client_id = _format_client_id(addr)
87
+
88
+ def _clear_client_stats(self):
89
+ with self._stats_lock:
90
+ self._client_started_at = None
91
+ self._client_id = None
92
+
93
+ def get_client_stats(self) -> dict:
94
+ """Return connected client count and per-client durations in seconds."""
95
+ with self._stats_lock:
96
+ started_at = self._client_started_at
97
+ client_id = self._client_id
98
+ if not started_at or not client_id or not self.connected:
99
+ return {"connected_clients": 0, "clients": {}}
100
+ duration = time.monotonic() - started_at
101
+ return {"connected_clients": 1, "clients": {client_id: duration}}
102
+
64
103
  def _accept_client(self) -> bool:
65
104
  """Accept an incoming connection; return True when a client connects."""
66
105
  try:
@@ -76,6 +115,7 @@ class ThreadedServer(threading.Thread, jsocket_base.JsonServer, metaclass=abc.AB
76
115
  logger.debug("server stopping; accept loop exiting (%s:%s)", self.address, self.port)
77
116
  self._is_alive = False
78
117
  return False
118
+ self._record_client_start()
79
119
  return True
80
120
 
81
121
  def _handle_client_messages(self):
@@ -99,6 +139,7 @@ class ThreadedServer(threading.Thread, jsocket_base.JsonServer, metaclass=abc.AB
99
139
  logger.debug("handler error (%s): %s", type(e).__name__, e)
100
140
  self._close_connection()
101
141
  break
142
+ self._clear_client_stats()
102
143
 
103
144
  def run(self):
104
145
  # Ensure the run loop is active even when run() is invoked directly
@@ -132,6 +173,7 @@ class ThreadedServer(threading.Thread, jsocket_base.JsonServer, metaclass=abc.AB
132
173
  @retval None
133
174
  """
134
175
  self._is_alive = False
176
+ self._clear_client_stats()
135
177
  logger.debug("Threaded Server stopped on %s:%s", self.address, self.port)
136
178
 
137
179
 
@@ -144,6 +186,8 @@ class ServerFactoryThread(threading.Thread, jsocket_base.JsonSocket, metaclass=a
144
186
  self.conn = None
145
187
  jsocket_base.JsonSocket.__init__(self, **kwargs)
146
188
  self._is_alive = False
189
+ self._client_started_at = None
190
+ self._client_id = None
147
191
 
148
192
  def swap_socket(self, new_sock):
149
193
  """ Swaps the existing socket with a new one. Useful for setting socket after a new connection.
@@ -153,6 +197,12 @@ class ServerFactoryThread(threading.Thread, jsocket_base.JsonSocket, metaclass=a
153
197
  """
154
198
  self.socket = new_sock
155
199
  self.conn = self.socket
200
+ try:
201
+ addr = new_sock.getpeername()
202
+ except OSError:
203
+ addr = None
204
+ self._client_id = _format_client_id(addr)
205
+ self._client_started_at = time.monotonic()
156
206
 
157
207
  def run(self):
158
208
  """ Should exit when client closes socket conn.
@@ -215,6 +265,7 @@ class ServerFactory(ThreadedServer):
215
265
  raise TypeError("serverThread not of type", ServerFactoryThread)
216
266
  self._thread_type = server_thread
217
267
  self._threads = []
268
+ self._threads_lock = threading.Lock()
218
269
  self._thread_args = kwargs
219
270
  self._thread_args.pop('address', None)
220
271
  self._thread_args.pop('port', None)
@@ -245,9 +296,21 @@ class ServerFactory(ThreadedServer):
245
296
  accepted_conn = self.conn
246
297
  # Reset server connection reference so we can accept again
247
298
  self._reset_connection_ref()
299
+ if not self._is_alive:
300
+ # Server is stopping; close the accepted connection without spawning a worker.
301
+ try:
302
+ accepted_conn.shutdown(socket.SHUT_RDWR)
303
+ except OSError:
304
+ pass
305
+ try:
306
+ accepted_conn.close()
307
+ except OSError:
308
+ pass
309
+ break
248
310
  tmp.swap_socket(accepted_conn)
249
311
  tmp.start()
250
- self._threads.append(tmp)
312
+ with self._threads_lock:
313
+ self._threads.append(tmp)
251
314
  break
252
315
 
253
316
  self._wait_to_exit()
@@ -255,14 +318,20 @@ class ServerFactory(ThreadedServer):
255
318
 
256
319
  def stop_all(self):
257
320
  """Stop and join all active worker threads."""
258
- for t in self._threads:
259
- if t.is_alive():
321
+ while True:
322
+ with self._threads_lock:
323
+ threads = [t for t in self._threads if t.is_alive()]
324
+ if not threads:
325
+ break
326
+ for t in threads:
260
327
  t.force_stop()
261
328
  t.join()
329
+ self._purge_threads()
262
330
 
263
331
  def _purge_threads(self):
264
332
  # Rebuild list to avoid mutating while iterating
265
- self._threads = [t for t in self._threads if t.is_alive()]
333
+ with self._threads_lock:
334
+ self._threads = [t for t in self._threads if t.is_alive()]
266
335
 
267
336
  def stop(self):
268
337
  # Stop accepting and stop all workers
@@ -279,6 +348,25 @@ class ServerFactory(ThreadedServer):
279
348
  time.sleep(0.2)
280
349
 
281
350
  def _get_num_of_active_threads(self):
282
- return len([True for x in self._threads if x.is_alive()])
351
+ with self._threads_lock:
352
+ threads = list(self._threads)
353
+ return len([True for x in threads if x.is_alive()])
354
+
355
+ def get_client_stats(self) -> dict:
356
+ """Return connected client count and per-client durations in seconds."""
357
+ with self._threads_lock:
358
+ threads = list(self._threads)
359
+ now = time.monotonic()
360
+ clients = {}
361
+ active = 0
362
+ for t in threads:
363
+ if not t.is_alive():
364
+ continue
365
+ active += 1
366
+ started_at = getattr(t, "_client_started_at", None)
367
+ client_id = getattr(t, "_client_id", None) or f"thread-{t.name}"
368
+ duration = now - started_at if started_at else 0.0
369
+ clients[client_id] = duration
370
+ return {"connected_clients": active, "clients": clients}
283
371
 
284
372
  active = property(_get_num_of_active_threads, doc="number of active threads")
@@ -0,0 +1,369 @@
1
+ Metadata-Version: 2.4
2
+ Name: jsocket
3
+ Version: 2.0.0
4
+ Summary: Python JSON Server & Client
5
+ Author-email: Christopher Piekarski <chris@cpiekarski.com>
6
+ Maintainer-email: Christopher Piekarski <chris@cpiekarski.com>
7
+ License: Apache License
8
+ Version 2.0, January 2004
9
+ http://www.apache.org/licenses/
10
+
11
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
12
+
13
+ 1. Definitions.
14
+
15
+ "License" shall mean the terms and conditions for use, reproduction,
16
+ and distribution as defined by Sections 1 through 9 of this document.
17
+
18
+ "Licensor" shall mean the copyright owner or entity authorized by
19
+ the copyright owner that is granting the License.
20
+
21
+ "Legal Entity" shall mean the union of the acting entity and all
22
+ other entities that control, are controlled by, or are under common
23
+ control with that entity. For the purposes of this definition,
24
+ "control" means (i) the power, direct or indirect, to cause the
25
+ direction or management of such entity, whether by contract or
26
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
27
+ outstanding shares, or (iii) beneficial ownership of such entity.
28
+
29
+ "You" (or "Your") shall mean an individual or Legal Entity
30
+ exercising permissions granted by this License.
31
+
32
+ "Source" form shall mean the preferred form for making modifications,
33
+ including but not limited to software source code, documentation
34
+ source, and configuration files.
35
+
36
+ "Object" form shall mean any form resulting from mechanical
37
+ transformation or translation of a Source form, including but
38
+ not limited to compiled object code, generated documentation,
39
+ and conversions to other media types.
40
+
41
+ "Work" shall mean the work of authorship, whether in Source or
42
+ Object form, made available under the License, as indicated by a
43
+ copyright notice that is included in or attached to the work
44
+ (an example is provided in the Appendix below).
45
+
46
+ "Derivative Works" shall mean any work, whether in Source or Object
47
+ form, that is based on (or derived from) the Work and for which the
48
+ editorial revisions, annotations, elaborations, or other modifications
49
+ represent, as a whole, an original work of authorship. For the purposes
50
+ of this License, Derivative Works shall not include works that remain
51
+ separable from, or merely link (or bind by name) to the interfaces of,
52
+ the Work and Derivative Works thereof.
53
+
54
+ "Contribution" shall mean any work of authorship, including
55
+ the original version of the Work and any modifications or additions
56
+ to that Work or Derivative Works thereof, that is intentionally
57
+ submitted to Licensor for inclusion in the Work by the copyright owner
58
+ or by an individual or Legal Entity authorized to submit on behalf of
59
+ the copyright owner. For the purposes of this definition, "submitted"
60
+ means any form of electronic, verbal, or written communication sent
61
+ to the Licensor or its representatives, including but not limited to
62
+ communication on electronic mailing lists, source code control systems,
63
+ and issue tracking systems that are managed by, or on behalf of, the
64
+ Licensor for the purpose of discussing and improving the Work, but
65
+ excluding communication that is conspicuously marked or otherwise
66
+ designated in writing by the copyright owner as "Not a Contribution."
67
+
68
+ "Contributor" shall mean Licensor and any individual or Legal Entity
69
+ on behalf of whom a Contribution has been received by Licensor and
70
+ subsequently incorporated within the Work.
71
+
72
+ 2. Grant of Copyright License. Subject to the terms and conditions of
73
+ this License, each Contributor hereby grants to You a perpetual,
74
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
75
+ copyright license to reproduce, prepare Derivative Works of,
76
+ publicly display, publicly perform, sublicense, and distribute the
77
+ Work and such Derivative Works in Source or Object form.
78
+
79
+ 3. Grant of Patent License. Subject to the terms and conditions of
80
+ this License, each Contributor hereby grants to You a perpetual,
81
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
82
+ (except as stated in this section) patent license to make, have made,
83
+ use, offer to sell, sell, import, and otherwise transfer the Work,
84
+ where such license applies only to those patent claims licensable
85
+ by such Contributor that are necessarily infringed by their
86
+ Contribution(s) alone or by combination of their Contribution(s)
87
+ with the Work to which such Contribution(s) was submitted. If You
88
+ institute patent litigation against any entity (including a
89
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
90
+ or a Contribution incorporated within the Work constitutes direct
91
+ or contributory patent infringement, then any patent licenses
92
+ granted to You under this License for that Work shall terminate
93
+ as of the date such litigation is filed.
94
+
95
+ 4. Redistribution. You may reproduce and distribute copies of the
96
+ Work or Derivative Works thereof in any medium, with or without
97
+ modifications, and in Source or Object form, provided that You
98
+ meet the following conditions:
99
+
100
+ (a) You must give any other recipients of the Work or
101
+ Derivative Works a copy of this License; and
102
+
103
+ (b) You must cause any modified files to carry prominent notices
104
+ stating that You changed the files; and
105
+
106
+ (c) You must retain, in the Source form of any Derivative Works
107
+ that You distribute, all copyright, patent, trademark, and
108
+ attribution notices from the Source form of the Work,
109
+ excluding those notices that do not pertain to any part of
110
+ the Derivative Works; and
111
+
112
+ (d) If the Work includes a "NOTICE" text file as part of its
113
+ distribution, then any Derivative Works that You distribute must
114
+ include a readable copy of the attribution notices contained
115
+ within such NOTICE file, excluding those notices that do not
116
+ pertain to any part of the Derivative Works, in at least one
117
+ of the following places: within a NOTICE text file distributed
118
+ as part of the Derivative Works; within the Source form or
119
+ documentation, if provided along with the Derivative Works; or,
120
+ within a display generated by the Derivative Works, if and
121
+ wherever such third-party notices normally appear. The contents
122
+ of the NOTICE file are for informational purposes only and
123
+ do not modify the License. You may add Your own attribution
124
+ notices within Derivative Works that You distribute, alongside
125
+ or as an addendum to the NOTICE text from the Work, provided
126
+ that such additional attribution notices cannot be construed
127
+ as modifying the License.
128
+
129
+ You may add Your own copyright statement to Your modifications and
130
+ may provide additional or different license terms and conditions
131
+ for use, reproduction, or distribution of Your modifications, or
132
+ for any such Derivative Works as a whole, provided Your use,
133
+ reproduction, and distribution of the Work otherwise complies with
134
+ the conditions stated in this License.
135
+
136
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
137
+ any Contribution intentionally submitted for inclusion in the Work
138
+ by You to the Licensor shall be under the terms and conditions of
139
+ this License, without any additional terms or conditions.
140
+ Notwithstanding the above, nothing herein shall supersede or modify
141
+ the terms of any separate license agreement you may have executed
142
+ with Licensor regarding such Contributions.
143
+
144
+ 6. Trademarks. This License does not grant permission to use the trade
145
+ names, trademarks, service marks, or product names of the Licensor,
146
+ except as required for reasonable and customary use in describing the
147
+ origin of the Work and reproducing the content of the NOTICE file.
148
+
149
+ 7. Disclaimer of Warranty. Unless required by applicable law or
150
+ agreed to in writing, Licensor provides the Work (and each
151
+ Contributor provides its Contributions) on an "AS IS" BASIS,
152
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
153
+ implied, including, without limitation, any warranties or conditions
154
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
155
+ PARTICULAR PURPOSE. You are solely responsible for determining the
156
+ appropriateness of using or redistributing the Work and assume any
157
+ risks associated with Your exercise of permissions under this License.
158
+
159
+ 8. Limitation of Liability. In no event and under no legal theory,
160
+ whether in tort (including negligence), contract, or otherwise,
161
+ unless required by applicable law (such as deliberate and grossly
162
+ negligent acts) or agreed to in writing, shall any Contributor be
163
+ liable to You for damages, including any direct, indirect, special,
164
+ incidental, or consequential damages of any character arising as a
165
+ result of this License or out of the use or inability to use the
166
+ Work (including but not limited to damages for loss of goodwill,
167
+ work stoppage, computer failure or malfunction, or any and all
168
+ other commercial damages or losses), even if such Contributor
169
+ has been advised of the possibility of such damages.
170
+
171
+ 9. Accepting Warranty or Additional Liability. While redistributing
172
+ the Work or Derivative Works thereof, You may choose to offer,
173
+ and charge a fee for, acceptance of support, warranty, indemnity,
174
+ or other liability obligations and/or rights consistent with this
175
+ License. However, in accepting such obligations, You may act only
176
+ on Your own behalf and on Your sole responsibility, not on behalf
177
+ of any other Contributor, and only if You agree to indemnify,
178
+ defend, and hold each Contributor harmless for any liability
179
+ incurred by, or claims asserted against, such Contributor by reason
180
+ of your accepting any such warranty or additional liability.
181
+
182
+ END OF TERMS AND CONDITIONS
183
+
184
+ APPENDIX: How to apply the Apache License to your work.
185
+
186
+ To apply the Apache License to your work, attach the following
187
+ boilerplate notice, with the fields enclosed by brackets "[]"
188
+ replaced with your own identifying information. (Don't include
189
+ the brackets!) The text should be enclosed in the appropriate
190
+ comment syntax for the file format. We also recommend that a
191
+ file or class name and description of purpose be included on the
192
+ same "printed page" as the copyright notice for easier
193
+ identification within third-party archives.
194
+
195
+ Copyright [2011] [Christopher Piekarski]
196
+
197
+ Licensed under the Apache License, Version 2.0 (the "License");
198
+ you may not use this file except in compliance with the License.
199
+ You may obtain a copy of the License at
200
+
201
+ http://www.apache.org/licenses/LICENSE-2.0
202
+
203
+ Unless required by applicable law or agreed to in writing, software
204
+ distributed under the License is distributed on an "AS IS" BASIS,
205
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
206
+ See the License for the specific language governing permissions and
207
+ limitations under the License.
208
+
209
+ Project-URL: Homepage, https://cpiekarski.com/2012/01/25/python-json-client-server-redux/
210
+ Keywords: json,socket,server,client
211
+ Classifier: Intended Audience :: Developers
212
+ Classifier: Programming Language :: Python :: 3.9
213
+ Classifier: Operating System :: OS Independent
214
+ Classifier: Development Status :: 5 - Production/Stable
215
+ Classifier: Topic :: System :: Networking
216
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
217
+ Classifier: Topic :: System :: Distributed Computing
218
+ Classifier: Topic :: System :: Hardware :: Symmetric Multi-processing
219
+ Requires-Python: >=3.8
220
+ Description-Content-Type: text/markdown
221
+ License-File: LICENSE
222
+ Dynamic: license-file
223
+
224
+ python-json-socket (jsocket)
225
+ ============================
226
+
227
+ [![CI](https://github.com/chris-piekarski/python-json-socket/actions/workflows/ci.yml/badge.svg)](https://github.com/chris-piekarski/python-json-socket/actions/workflows/ci.yml)
228
+ ![PyPI](https://img.shields.io/pypi/v/jsocket.svg)
229
+ ![Python Versions](https://img.shields.io/pypi/pyversions/jsocket.svg)
230
+ ![License](https://img.shields.io/pypi/l/jsocket.svg)
231
+
232
+ Simple JSON-over-TCP sockets for Python. This library provides:
233
+
234
+ - JsonClient/JsonServer: length‑prefixed JSON message framing over TCP
235
+ - ThreadedServer: a single-connection server running in its own thread
236
+ - ServerFactory/ServerFactoryThread: a per‑connection worker model for multiple clients
237
+
238
+ It aims to be small, predictable, and easy to integrate in tests or small services.
239
+
240
+
241
+ Install
242
+ -------
243
+
244
+ ```
245
+ pip install jsocket
246
+ ```
247
+
248
+ Requires Python 3.8+.
249
+
250
+
251
+ Quickstart
252
+ ----------
253
+
254
+ Echo server with `ThreadedServer` and a client:
255
+
256
+ ```python
257
+ import time
258
+ import jsocket
259
+
260
+ class Echo(jsocket.ThreadedServer):
261
+ def __init__(self, **kwargs):
262
+ super().__init__(**kwargs)
263
+ self.timeout = 2.0
264
+
265
+ # Return a dict to send a response back to the client
266
+ def _process_message(self, obj):
267
+ if isinstance(obj, dict) and 'echo' in obj:
268
+ return obj
269
+ return None
270
+
271
+ # Bind to an ephemeral port (port=0)
272
+ server = Echo(address='127.0.0.1', port=0)
273
+ _, port = server.socket.getsockname()
274
+ server.start()
275
+
276
+ client = jsocket.JsonClient(address='127.0.0.1', port=port)
277
+ assert client.connect() is True
278
+
279
+ payload = {"echo": "hello"}
280
+ client.send_obj(payload)
281
+ assert client.read_obj() == payload
282
+
283
+ client.close()
284
+ server.stop()
285
+ server.join()
286
+ ```
287
+
288
+ Per‑connection workers with `ServerFactory`:
289
+
290
+ ```python
291
+ import jsocket
292
+
293
+ class Worker(jsocket.ServerFactoryThread):
294
+ def __init__(self):
295
+ super().__init__()
296
+ self.timeout = 2.0
297
+
298
+ def _process_message(self, obj):
299
+ if isinstance(obj, dict) and 'message' in obj:
300
+ return {"reply": f"got: {obj['message']}"}
301
+
302
+ server = jsocket.ServerFactory(Worker, address='127.0.0.1', port=5489)
303
+ server.start()
304
+ # Connect one or more clients; one Worker is spawned per connection
305
+ ```
306
+
307
+
308
+ API Highlights
309
+ --------------
310
+
311
+ - JsonClient:
312
+ - `connect()` returns True on success
313
+ - `send_obj(dict)` sends a JSON object
314
+ - `read_obj()` blocks until a full message is received; raises `socket.timeout` or `RuntimeError("socket connection broken")`
315
+ - `timeout` property controls socket timeouts
316
+
317
+ - ThreadedServer:
318
+ - Subclass and implement `_process_message(self, obj) -> Optional[dict]`
319
+ - Return a dict to send a response; return `None` to send nothing
320
+ - `start()`, `stop()`, `join()` manage the server thread
321
+ - `send_obj(dict)` sends to the currently connected client
322
+
323
+ - ServerFactory / ServerFactoryThread:
324
+ - `ServerFactoryThread` is a worker that handles one client connection
325
+ - `ServerFactory` accepts connections and spawns a worker per client
326
+
327
+
328
+ Examples and Tests
329
+ ------------------
330
+
331
+ - Examples: see `examples/example_servers.py` and `scripts/smoke_test.py`
332
+ - Pytest: end-to-end and listener tests under `tests/`
333
+ - Run: `pytest -q`
334
+
335
+
336
+ Behavior-Driven Tests (Behave)
337
+ ------------------------------
338
+
339
+ - Steps live under `features/steps/` and environment hooks in `features/environment.py`.
340
+ - To run Behave scenarios, add one or more `.feature` files under `features/` and run:
341
+ - `pip install -r requirements-dev.txt`
342
+ - `PYTHONPATH=. behave -f progress2`
343
+ - A minimal example feature:
344
+
345
+ ```gherkin
346
+ Feature: Echo round-trip
347
+ Scenario: client/server echo
348
+ Given I start the server
349
+ And I connect the client
350
+ When the client sends the object {"echo": "hi"}
351
+ Then the client sees a message {"echo": "hi"}
352
+ ```
353
+
354
+
355
+ Notes
356
+ -----
357
+
358
+ - Breaking change: version 2.0.0 uses a new framing header (magic + length + CRC32). v1 clients are incompatible.
359
+ - Message framing uses a 12‑byte header: 4‑byte magic, 4‑byte big‑endian length, and 4‑byte CRC32 of the payload, followed by a JSON payload encoded as UTF‑8.
360
+ - `max_message_size` defaults to 10MB; set `.max_message_size` to adjust or set to `None` to disable.
361
+ - On disconnect, reads raise `RuntimeError("socket connection broken")` so callers can distinguish cleanly from timeouts.
362
+ - Binding with `port=0` lets the OS choose an ephemeral port; find it with `server.socket.getsockname()`.
363
+
364
+
365
+ Links
366
+ -----
367
+
368
+ - PyPI: https://pypi.org/project/jsocket/
369
+ - License: see `LICENSE`
@@ -0,0 +1,9 @@
1
+ jsocket/__init__.py,sha256=V2M4mp2IwcL1Zy_yoD-6Y5h7PO2sdt5Plf1U0Xw27N8,2870
2
+ jsocket/_version.py,sha256=G_8HyCR_7wKtd1vhEQPneS5oPZmjTSOtVVENsHtdYjU,46
3
+ jsocket/jsocket_base.py,sha256=LZdIiPKLi_iC1pSd3NjgJQrEzQ3hSgnhxIihVMuRFLw,11047
4
+ jsocket/tserver.py,sha256=h19so2UgUc1RIMmkNcJamwZ7gbFFGmaSJqrI2l6XUts,14098
5
+ jsocket-2.0.0.dist-info/licenses/LICENSE,sha256=TIwob4kUNx1DKZ0NVKToEDAFgWsevvTgtZgr_obkDhg,11355
6
+ jsocket-2.0.0.dist-info/METADATA,sha256=1g9-4-2lrq_RpDGeNtZyt8yswhQjG7QXezp4kBPOM9o,18303
7
+ jsocket-2.0.0.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
8
+ jsocket-2.0.0.dist-info/top_level.txt,sha256=QqfmeUi7avy9cdcsVVvG68CP-4mfg_P6E7OuBuNEcN4,8
9
+ jsocket-2.0.0.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: bdist_wheel (0.37.1)
2
+ Generator: setuptools (80.10.2)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,27 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: jsocket
3
- Version: 1.9.5
4
- Summary: Python JSON Server & Client
5
- Home-page: https://cpiekarski.com/2012/01/25/python-json-client-server-redux/
6
- Author: Christopher Piekarski
7
- Author-email: chris@cpiekarski.com
8
- Maintainer: Christopher Piekarski
9
- Maintainer-email: chris@cpiekarski.com
10
- License: OSI Approved Apache Software License
11
- Keywords: json,socket,server,client
12
- Platform: UNKNOWN
13
- Classifier: Intended Audience :: Developers
14
- Classifier: License :: OSI Approved :: Apache Software License
15
- Classifier: Programming Language :: Python :: 3.9
16
- Classifier: Operating System :: OS Independent
17
- Classifier: Development Status :: 5 - Production/Stable
18
- Classifier: Topic :: System :: Networking
19
- Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
20
- Classifier: Topic :: System :: Distributed Computing
21
- Classifier: Topic :: System :: Hardware :: Symmetric Multi-processing
22
- Provides: jsocket
23
- Requires-Python: >=3.8
24
- License-File: LICENSE
25
-
26
- UNKNOWN
27
-
@@ -1,8 +0,0 @@
1
- jsocket/__init__.py,sha256=Im4nFil0iBOXF0G5K5I2nVMkSDIlGNev-rOjy3XUwn8,2836
2
- jsocket/jsocket_base.py,sha256=65-0DMdgQKymiE3poBpvRnyTMgEv3-VOfqWe-C-6ge4,8025
3
- jsocket/tserver.py,sha256=bez8pKWwzPQXD0R33sTV-6Z579DS4vfQnnPkklzxt64,10746
4
- jsocket-1.9.5.dist-info/LICENSE,sha256=TIwob4kUNx1DKZ0NVKToEDAFgWsevvTgtZgr_obkDhg,11355
5
- jsocket-1.9.5.dist-info/METADATA,sha256=hV3r6UToy38ZkkrSi8ohRGndzCN_xYa8329Ue_hUhXQ,983
6
- jsocket-1.9.5.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92
7
- jsocket-1.9.5.dist-info/top_level.txt,sha256=QqfmeUi7avy9cdcsVVvG68CP-4mfg_P6E7OuBuNEcN4,8
8
- jsocket-1.9.5.dist-info/RECORD,,