wifi-server 1.0.0__tar.gz

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.
@@ -0,0 +1,17 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Aquilesinho
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
@@ -0,0 +1,219 @@
1
+ Metadata-Version: 2.4
2
+ Name: wifi-server
3
+ Version: 1.0.0
4
+ Summary: Simple LAN communication for Python multiplayer projects
5
+ Author: Aquilesinho
6
+ License: MIT
7
+ Keywords: multiplayer,network,lan,pygame
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Operating System :: OS Independent
10
+ Requires-Python: >=3.9
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Dynamic: license-file
14
+
15
+ # wifi-server
16
+
17
+ Biblioteca Python para comunicação multiplayer simples entre computadores na mesma rede local (LAN), usando descoberta UDP e comunicação TCP.
18
+
19
+ > Projeto inicial baseado no código fornecido. A API e os exemplos abaixo descrevem o comportamento implementado nesta versão.
20
+
21
+ ## Instalação
22
+
23
+ ```bash
24
+ pip install wifi-server
25
+ ```
26
+
27
+ ## Importação
28
+
29
+ ```python
30
+ import wifi
31
+ ```
32
+
33
+ ## Visão geral
34
+
35
+ - `wifi.host(port)`: cria um servidor.
36
+ - `server.on()`: inicia o servidor.
37
+ - `wifi.connect(port)`: procura e conecta ao servidor na rede local.
38
+ - `wifi.send(value, name)`: envia/atualiza um valor associado a um nome.
39
+ - `wifi.get(name, default=None)`: lê o último valor recebido/armazenado.
40
+ - `wifi.on(name, callback)`: registra callback para atualizações.
41
+ - `wifi.remove(name)`: remove um valor compartilhado.
42
+ - `wifi.reset()`: limpa todos os valores compartilhados.
43
+ - `wifi.close()` ou `server.close()`: encerra a conexão ou servidor.
44
+
45
+ ## Criando um servidor (Host)
46
+
47
+ ```python
48
+ import wifi
49
+
50
+ server = wifi.host(1234)
51
+ server.on()
52
+
53
+ # O servidor também pode enviar dados:
54
+ wifi.send("Olá!", "mensagem")
55
+ ```
56
+
57
+ `wifi.host(port)` cria e retorna uma instância de `Server`. `server.on()` inicia os serviços de descoberta UDP e conexão TCP em threads de fundo e retorna a própria instância.
58
+
59
+ ## Conectando como Client
60
+
61
+ ```python
62
+ import wifi
63
+
64
+ wifi.connect(1234)
65
+ wifi.send("Olá, Host!", "mensagem")
66
+ ```
67
+
68
+ `wifi.connect(port)` envia uma solicitação de descoberta UDP por broadcast e tenta conectar ao servidor encontrado na mesma porta. Se não encontrar o servidor, gera `ConnectionError`.
69
+
70
+ ## Enviando dados
71
+
72
+ ```python
73
+ wifi.send(valor, nome)
74
+ ```
75
+
76
+ Associado a um nome, o valor é enviado e armazenado no estado compartilhado.
77
+
78
+ Tipos suportados pelo código atual:
79
+
80
+ - `bool`
81
+ - `int`
82
+ - `float`
83
+ - `str`
84
+ - `bytes`
85
+ - `list`
86
+ - `tuple` (serializado como JSON; ao receber, é decodificado como lista)
87
+
88
+ Exemplos:
89
+
90
+ ```python
91
+ wifi.send(100, "pontuação")
92
+ wifi.send(3.14, "velocidade")
93
+ wifi.send(True, "pronto")
94
+ wifi.send("Olá", "texto")
95
+ wifi.send(b"\x00\x01", "bytes")
96
+ wifi.send([10, 20], "posição")
97
+ wifi.send((10, 20), "posição_tupla")
98
+ ```
99
+
100
+ Tipos não suportados geram `TypeError`.
101
+
102
+ ## Recebendo / consultando dados
103
+
104
+ ```python
105
+ valor = wifi.get("posição")
106
+ ```
107
+
108
+ `wifi.get(name, default=None)` retorna o valor mais recente armazenado para o nome ou `default` se o nome não existir.
109
+
110
+ ```python
111
+ posição = wifi.get("posição", [0, 0])
112
+ ```
113
+
114
+ ## Callbacks
115
+
116
+ ```python
117
+ def ao_receber(valor):
118
+ print("Atualização:", valor)
119
+
120
+ wifi.on("posição", ao_receber)
121
+ ```
122
+
123
+ `wifi.on(name, callback)` registra uma função que será chamada quando aquele nome for atualizado por um pacote recebido ou aplicado localmente. O callback recebe o valor como único argumento.
124
+
125
+ ## Remover um valor
126
+
127
+ ```python
128
+ wifi.remove("posição")
129
+ ```
130
+
131
+ `wifi.remove(name)` remove o nome do estado compartilhado e envia o comando de remoção aos outros participantes.
132
+
133
+ ## Limpar todos os valores
134
+
135
+ ```python
136
+ wifi.reset()
137
+ ```
138
+
139
+ `wifi.reset()` limpa o estado compartilhado inteiro e envia o comando de reset.
140
+
141
+ ## Encerrar um Client
142
+
143
+ ```python
144
+ wifi.close()
145
+ ```
146
+
147
+ `wifi.close()` encerra o socket do cliente e interrompe o loop de recebimento.
148
+
149
+ ## Encerrar um Host
150
+
151
+ ```python
152
+ server.close()
153
+ ```
154
+
155
+ `Server.close()` encerra os sockets do servidor, fecha os clientes conectados e interrompe os serviços.
156
+
157
+ ## API de Host
158
+
159
+ ### `wifi.host(port)`
160
+
161
+ Cria uma instância de `Server` para a porta informada.
162
+
163
+ ### `server.on()`
164
+
165
+ Inicia o Host. Retorna `server`, permitindo encadeamento:
166
+
167
+ ```python
168
+ wifi.host(1234).on()
169
+ ```
170
+
171
+ ### `server.close()`
172
+
173
+ Fecha o servidor e os clientes conectados.
174
+
175
+ ## Exemplo: posição de jogador
176
+
177
+ Host:
178
+
179
+ ```python
180
+ import wifi
181
+
182
+ server = wifi.host(1234)
183
+ server.on()
184
+
185
+ wifi.send([100, 200], "Player1Pos")
186
+ ```
187
+
188
+ Client:
189
+
190
+ ```python
191
+ import wifi
192
+
193
+ wifi.connect(1234)
194
+
195
+ posição = wifi.get("Player1Pos", [0, 0])
196
+ ```
197
+
198
+ ## Arquivos `.wifi`
199
+
200
+ Ao iniciar o Host, a biblioteca cria ou verifica um arquivo de identificação em:
201
+
202
+ `%LOCALAPPDATA%\Aquilesinho\wifi\<porta>.wifi`
203
+
204
+ O arquivo contém uma assinatura e a porta do Host.
205
+
206
+ ## Observações e limitações desta versão
207
+
208
+ - A descoberta é feita por broadcast UDP, portanto a rede e o firewall precisam permitir a comunicação.
209
+ - O sistema foi projetado para uso em rede local.
210
+ - O estado é armazenado em memória; não é um banco de dados persistente.
211
+ - Os callbacks executam no contexto da thread que recebe/aplica o pacote. Se usar Pygame, considere apenas guardar os dados no callback e processá-los no loop principal.
212
+ - A implementação atual não fornece autenticação nem criptografia. Não envie informações sensíveis.
213
+ - `wifi.connect(port)` usa timeout de 3 segundos na descoberta UDP.
214
+ - `wifi.send()` não retorna confirmação de entrega.
215
+ - O servidor repassa as atualizações recebidas para os demais clientes e também aplica as atualizações ao estado local.
216
+
217
+ ## Licença
218
+
219
+ MIT.
@@ -0,0 +1,205 @@
1
+ # wifi-server
2
+
3
+ Biblioteca Python para comunicação multiplayer simples entre computadores na mesma rede local (LAN), usando descoberta UDP e comunicação TCP.
4
+
5
+ > Projeto inicial baseado no código fornecido. A API e os exemplos abaixo descrevem o comportamento implementado nesta versão.
6
+
7
+ ## Instalação
8
+
9
+ ```bash
10
+ pip install wifi-server
11
+ ```
12
+
13
+ ## Importação
14
+
15
+ ```python
16
+ import wifi
17
+ ```
18
+
19
+ ## Visão geral
20
+
21
+ - `wifi.host(port)`: cria um servidor.
22
+ - `server.on()`: inicia o servidor.
23
+ - `wifi.connect(port)`: procura e conecta ao servidor na rede local.
24
+ - `wifi.send(value, name)`: envia/atualiza um valor associado a um nome.
25
+ - `wifi.get(name, default=None)`: lê o último valor recebido/armazenado.
26
+ - `wifi.on(name, callback)`: registra callback para atualizações.
27
+ - `wifi.remove(name)`: remove um valor compartilhado.
28
+ - `wifi.reset()`: limpa todos os valores compartilhados.
29
+ - `wifi.close()` ou `server.close()`: encerra a conexão ou servidor.
30
+
31
+ ## Criando um servidor (Host)
32
+
33
+ ```python
34
+ import wifi
35
+
36
+ server = wifi.host(1234)
37
+ server.on()
38
+
39
+ # O servidor também pode enviar dados:
40
+ wifi.send("Olá!", "mensagem")
41
+ ```
42
+
43
+ `wifi.host(port)` cria e retorna uma instância de `Server`. `server.on()` inicia os serviços de descoberta UDP e conexão TCP em threads de fundo e retorna a própria instância.
44
+
45
+ ## Conectando como Client
46
+
47
+ ```python
48
+ import wifi
49
+
50
+ wifi.connect(1234)
51
+ wifi.send("Olá, Host!", "mensagem")
52
+ ```
53
+
54
+ `wifi.connect(port)` envia uma solicitação de descoberta UDP por broadcast e tenta conectar ao servidor encontrado na mesma porta. Se não encontrar o servidor, gera `ConnectionError`.
55
+
56
+ ## Enviando dados
57
+
58
+ ```python
59
+ wifi.send(valor, nome)
60
+ ```
61
+
62
+ Associado a um nome, o valor é enviado e armazenado no estado compartilhado.
63
+
64
+ Tipos suportados pelo código atual:
65
+
66
+ - `bool`
67
+ - `int`
68
+ - `float`
69
+ - `str`
70
+ - `bytes`
71
+ - `list`
72
+ - `tuple` (serializado como JSON; ao receber, é decodificado como lista)
73
+
74
+ Exemplos:
75
+
76
+ ```python
77
+ wifi.send(100, "pontuação")
78
+ wifi.send(3.14, "velocidade")
79
+ wifi.send(True, "pronto")
80
+ wifi.send("Olá", "texto")
81
+ wifi.send(b"\x00\x01", "bytes")
82
+ wifi.send([10, 20], "posição")
83
+ wifi.send((10, 20), "posição_tupla")
84
+ ```
85
+
86
+ Tipos não suportados geram `TypeError`.
87
+
88
+ ## Recebendo / consultando dados
89
+
90
+ ```python
91
+ valor = wifi.get("posição")
92
+ ```
93
+
94
+ `wifi.get(name, default=None)` retorna o valor mais recente armazenado para o nome ou `default` se o nome não existir.
95
+
96
+ ```python
97
+ posição = wifi.get("posição", [0, 0])
98
+ ```
99
+
100
+ ## Callbacks
101
+
102
+ ```python
103
+ def ao_receber(valor):
104
+ print("Atualização:", valor)
105
+
106
+ wifi.on("posição", ao_receber)
107
+ ```
108
+
109
+ `wifi.on(name, callback)` registra uma função que será chamada quando aquele nome for atualizado por um pacote recebido ou aplicado localmente. O callback recebe o valor como único argumento.
110
+
111
+ ## Remover um valor
112
+
113
+ ```python
114
+ wifi.remove("posição")
115
+ ```
116
+
117
+ `wifi.remove(name)` remove o nome do estado compartilhado e envia o comando de remoção aos outros participantes.
118
+
119
+ ## Limpar todos os valores
120
+
121
+ ```python
122
+ wifi.reset()
123
+ ```
124
+
125
+ `wifi.reset()` limpa o estado compartilhado inteiro e envia o comando de reset.
126
+
127
+ ## Encerrar um Client
128
+
129
+ ```python
130
+ wifi.close()
131
+ ```
132
+
133
+ `wifi.close()` encerra o socket do cliente e interrompe o loop de recebimento.
134
+
135
+ ## Encerrar um Host
136
+
137
+ ```python
138
+ server.close()
139
+ ```
140
+
141
+ `Server.close()` encerra os sockets do servidor, fecha os clientes conectados e interrompe os serviços.
142
+
143
+ ## API de Host
144
+
145
+ ### `wifi.host(port)`
146
+
147
+ Cria uma instância de `Server` para a porta informada.
148
+
149
+ ### `server.on()`
150
+
151
+ Inicia o Host. Retorna `server`, permitindo encadeamento:
152
+
153
+ ```python
154
+ wifi.host(1234).on()
155
+ ```
156
+
157
+ ### `server.close()`
158
+
159
+ Fecha o servidor e os clientes conectados.
160
+
161
+ ## Exemplo: posição de jogador
162
+
163
+ Host:
164
+
165
+ ```python
166
+ import wifi
167
+
168
+ server = wifi.host(1234)
169
+ server.on()
170
+
171
+ wifi.send([100, 200], "Player1Pos")
172
+ ```
173
+
174
+ Client:
175
+
176
+ ```python
177
+ import wifi
178
+
179
+ wifi.connect(1234)
180
+
181
+ posição = wifi.get("Player1Pos", [0, 0])
182
+ ```
183
+
184
+ ## Arquivos `.wifi`
185
+
186
+ Ao iniciar o Host, a biblioteca cria ou verifica um arquivo de identificação em:
187
+
188
+ `%LOCALAPPDATA%\Aquilesinho\wifi\<porta>.wifi`
189
+
190
+ O arquivo contém uma assinatura e a porta do Host.
191
+
192
+ ## Observações e limitações desta versão
193
+
194
+ - A descoberta é feita por broadcast UDP, portanto a rede e o firewall precisam permitir a comunicação.
195
+ - O sistema foi projetado para uso em rede local.
196
+ - O estado é armazenado em memória; não é um banco de dados persistente.
197
+ - Os callbacks executam no contexto da thread que recebe/aplica o pacote. Se usar Pygame, considere apenas guardar os dados no callback e processá-los no loop principal.
198
+ - A implementação atual não fornece autenticação nem criptografia. Não envie informações sensíveis.
199
+ - `wifi.connect(port)` usa timeout de 3 segundos na descoberta UDP.
200
+ - `wifi.send()` não retorna confirmação de entrega.
201
+ - O servidor repassa as atualizações recebidas para os demais clientes e também aplica as atualizações ao estado local.
202
+
203
+ ## Licença
204
+
205
+ MIT.
@@ -0,0 +1,20 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "wifi-server"
7
+ version = "1.0.0"
8
+ description = "Simple LAN communication for Python multiplayer projects"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "Aquilesinho" }]
13
+ keywords = ["multiplayer", "network", "lan", "pygame"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Operating System :: OS Independent",
17
+ ]
18
+
19
+ [tool.setuptools]
20
+ packages = ["wifi"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1 @@
1
+ from .main import *
@@ -0,0 +1,515 @@
1
+ import socket
2
+ import struct
3
+ import threading
4
+ import os
5
+ import json
6
+
7
+ _MAGIC = b"WIFI01"
8
+ _DISCOVERY = b"WIFI_DISCOVER01"
9
+ _REPLY = b"WIFI_SERVER01"
10
+
11
+ _states = {}
12
+ _callbacks = {}
13
+ _lock = threading.Lock()
14
+
15
+ _client = None
16
+ _running = False
17
+ _server_instance = None
18
+
19
+
20
+ def _encode(name, value=None, command=0):
21
+ name = name.encode("utf-8")
22
+
23
+ if command == 1:
24
+ type_id = 6
25
+ data = b""
26
+
27
+ elif command == 2:
28
+ type_id = 7
29
+ data = b""
30
+
31
+ elif isinstance(value, bool):
32
+ type_id = 1
33
+ data = struct.pack("!B", value)
34
+
35
+ elif isinstance(value, int):
36
+ type_id = 2
37
+ data = struct.pack("!q", value)
38
+
39
+ elif isinstance(value, float):
40
+ type_id = 3
41
+ data = struct.pack("!d", value)
42
+
43
+ elif isinstance(value, str):
44
+ type_id = 4
45
+ data = value.encode("utf-8")
46
+
47
+ elif isinstance(value, bytes):
48
+ type_id = 5
49
+ data = value
50
+
51
+ elif isinstance(value, (list, tuple)):
52
+ type_id = 8
53
+ data = json.dumps(value).encode("utf-8")
54
+
55
+ else:
56
+ raise TypeError("Tipo de dado não suportado")
57
+
58
+ packet = struct.pack("!BH", type_id, len(name))
59
+ packet += name
60
+ packet += struct.pack("!I", len(data))
61
+ packet += data
62
+
63
+ return struct.pack("!I", len(packet)) + packet
64
+
65
+
66
+ def _decode(packet):
67
+ type_id, name_len = struct.unpack("!BH", packet[:3])
68
+
69
+ name = packet[3:3 + name_len].decode("utf-8")
70
+
71
+ pos = 3 + name_len
72
+ data_len = struct.unpack("!I", packet[pos:pos + 4])[0]
73
+ data = packet[pos + 4:pos + 4 + data_len]
74
+
75
+ if type_id == 1:
76
+ value = struct.unpack("!B", data)[0] == 1
77
+
78
+ elif type_id == 2:
79
+ value = struct.unpack("!q", data)[0]
80
+
81
+ elif type_id == 3:
82
+ value = struct.unpack("!d", data)[0]
83
+
84
+ elif type_id == 4:
85
+ value = data.decode("utf-8")
86
+
87
+ elif type_id == 5:
88
+ value = data
89
+
90
+ elif type_id == 8:
91
+ value = json.loads(data.decode("utf-8"))
92
+
93
+ elif type_id in (6, 7):
94
+ value = None
95
+
96
+ else:
97
+ raise ValueError("Tipo desconhecido")
98
+
99
+ return type_id, name, value
100
+
101
+
102
+ def _recv_exact(sock, size):
103
+ data = bytearray()
104
+
105
+ while len(data) < size:
106
+ part = sock.recv(size - len(data))
107
+
108
+ if not part:
109
+ return None
110
+
111
+ data.extend(part)
112
+
113
+ return bytes(data)
114
+
115
+
116
+ def _recv_packet(sock):
117
+ header = _recv_exact(sock, 4)
118
+
119
+ if header is None:
120
+ return None
121
+
122
+ size = struct.unpack("!I", header)[0]
123
+
124
+ if size > 10_000_000:
125
+ return None
126
+
127
+ return _recv_exact(sock, size)
128
+
129
+
130
+ def _apply_packet(packet):
131
+ type_id, name, value = _decode(packet)
132
+
133
+ with _lock:
134
+ if type_id == 6:
135
+ _states.pop(name, None)
136
+ callback = None
137
+
138
+ elif type_id == 7:
139
+ _states.clear()
140
+ callback = None
141
+
142
+ else:
143
+ _states[name] = value
144
+ callback = _callbacks.get(name)
145
+
146
+ if callback:
147
+ callback(value)
148
+
149
+
150
+ def _receive_loop(sock):
151
+ global _running
152
+
153
+ while _running:
154
+ try:
155
+ packet = _recv_packet(sock)
156
+
157
+ if packet is None:
158
+ break
159
+
160
+ _apply_packet(packet)
161
+
162
+ except:
163
+ break
164
+
165
+ _running = False
166
+
167
+
168
+ def send(value, name):
169
+ packet = _encode(name, value)
170
+
171
+ # CLIENTE
172
+ if _client is not None:
173
+ try:
174
+ _client.sendall(packet)
175
+ except:
176
+ pass
177
+
178
+ return
179
+
180
+ # HOST
181
+ if _server_instance is not None:
182
+ _server_instance._local_send(packet)
183
+
184
+
185
+ def get(name, default=None):
186
+ with _lock:
187
+ return _states.get(name, default)
188
+
189
+
190
+ def on(name, callback):
191
+ with _lock:
192
+ _callbacks[name] = callback
193
+
194
+
195
+ def remove(name):
196
+ packet = _encode(name, command=1)
197
+
198
+ if _client is not None:
199
+ try:
200
+ _client.sendall(packet)
201
+ except:
202
+ pass
203
+
204
+ return
205
+
206
+ if _server_instance is not None:
207
+ _server_instance._local_send(packet)
208
+
209
+
210
+ def reset():
211
+ packet = _encode("", command=2)
212
+
213
+ if _client is not None:
214
+ try:
215
+ _client.sendall(packet)
216
+ except:
217
+ pass
218
+
219
+ return
220
+
221
+ if _server_instance is not None:
222
+ _server_instance._local_send(packet)
223
+
224
+
225
+ def connect(port):
226
+ global _client, _running
227
+
228
+ discovery = socket.socket(
229
+ socket.AF_INET,
230
+ socket.SOCK_DGRAM
231
+ )
232
+
233
+ discovery.setsockopt(
234
+ socket.SOL_SOCKET,
235
+ socket.SO_BROADCAST,
236
+ 1
237
+ )
238
+
239
+ discovery.settimeout(3)
240
+
241
+ try:
242
+ discovery.sendto(
243
+ _DISCOVERY,
244
+ ("255.255.255.255", port)
245
+ )
246
+
247
+ response, address = discovery.recvfrom(1024)
248
+
249
+ if response != _REPLY:
250
+ raise ConnectionError("Servidor inválido")
251
+
252
+ server_ip = address[0]
253
+
254
+ except socket.timeout:
255
+ discovery.close()
256
+ raise ConnectionError("Servidor não encontrado")
257
+
258
+ discovery.close()
259
+
260
+ _client = socket.socket(
261
+ socket.AF_INET,
262
+ socket.SOCK_STREAM
263
+ )
264
+
265
+ _client.connect((server_ip, port))
266
+
267
+ _running = True
268
+
269
+ threading.Thread(
270
+ target=_receive_loop,
271
+ args=(_client,),
272
+ daemon=True
273
+ ).start()
274
+
275
+
276
+ def close():
277
+ global _running, _client
278
+
279
+ _running = False
280
+
281
+ if _client:
282
+ try:
283
+ _client.shutdown(socket.SHUT_RDWR)
284
+ except:
285
+ pass
286
+
287
+ try:
288
+ _client.close()
289
+ except:
290
+ pass
291
+
292
+ _client = None
293
+
294
+
295
+ class Server:
296
+
297
+ def __init__(self, port):
298
+ self.port = port
299
+ self.clients = []
300
+ self.running = False
301
+ self.lock = threading.Lock()
302
+ self.tcp = None
303
+ self.udp = None
304
+
305
+ def on(self):
306
+ global _server_instance
307
+
308
+ if self.running:
309
+ return self
310
+
311
+ _server_instance = self
312
+ self.running = True
313
+
314
+ folder = os.path.join(
315
+ os.environ["LOCALAPPDATA"],
316
+ "Aquilesinho",
317
+ "wifi"
318
+ )
319
+
320
+ os.makedirs(folder, exist_ok=True)
321
+
322
+ path = os.path.join(
323
+ folder,
324
+ str(self.port) + ".wifi"
325
+ )
326
+
327
+ expected = _MAGIC + struct.pack("!H", self.port)
328
+
329
+ valid = False
330
+
331
+ if os.path.exists(path):
332
+ try:
333
+ with open(path, "rb") as file:
334
+ existing = file.read()
335
+
336
+ valid = existing == expected
337
+
338
+ except:
339
+ valid = False
340
+
341
+ if valid:
342
+ print("Arquivo .wifi reconhecido!")
343
+
344
+ else:
345
+ with open(path, "wb") as file:
346
+ file.write(expected)
347
+
348
+ print("Arquivo .wifi criado/atualizado!")
349
+
350
+ threading.Thread(
351
+ target=self._discovery,
352
+ daemon=True
353
+ ).start()
354
+
355
+ threading.Thread(
356
+ target=self._server,
357
+ daemon=True
358
+ ).start()
359
+
360
+ return self
361
+
362
+ def _local_send(self, packet):
363
+ payload = packet[4:]
364
+
365
+ _apply_packet(payload)
366
+ self._broadcast(payload)
367
+
368
+ def _broadcast(self, packet, exclude=None):
369
+ packet_out = struct.pack(
370
+ "!I",
371
+ len(packet)
372
+ ) + packet
373
+
374
+ with self.lock:
375
+ clients = list(self.clients)
376
+
377
+ for other in clients:
378
+ if other is exclude:
379
+ continue
380
+
381
+ try:
382
+ other.sendall(packet_out)
383
+
384
+ except:
385
+ pass
386
+
387
+ def _discovery(self):
388
+ sock = socket.socket(
389
+ socket.AF_INET,
390
+ socket.SOCK_DGRAM
391
+ )
392
+
393
+ self.udp = sock
394
+
395
+ sock.setsockopt(
396
+ socket.SOL_SOCKET,
397
+ socket.SO_REUSEADDR,
398
+ 1
399
+ )
400
+
401
+ try:
402
+ sock.bind(("", self.port))
403
+
404
+ except:
405
+ self.running = False
406
+ sock.close()
407
+ return
408
+
409
+ while self.running:
410
+ try:
411
+ data, address = sock.recvfrom(1024)
412
+
413
+ if data == _DISCOVERY:
414
+ sock.sendto(_REPLY, address)
415
+
416
+ except:
417
+ break
418
+
419
+ sock.close()
420
+
421
+ def _server(self):
422
+ sock = socket.socket(
423
+ socket.AF_INET,
424
+ socket.SOCK_STREAM
425
+ )
426
+
427
+ self.tcp = sock
428
+
429
+ sock.setsockopt(
430
+ socket.SOL_SOCKET,
431
+ socket.SO_REUSEADDR,
432
+ 1
433
+ )
434
+
435
+ try:
436
+ sock.bind(("0.0.0.0", self.port))
437
+ sock.listen()
438
+
439
+ except:
440
+ self.running = False
441
+ sock.close()
442
+ return
443
+
444
+ while self.running:
445
+ try:
446
+ client, address = sock.accept()
447
+
448
+ with self.lock:
449
+ self.clients.append(client)
450
+
451
+ threading.Thread(
452
+ target=self._handle,
453
+ args=(client,),
454
+ daemon=True
455
+ ).start()
456
+
457
+ except:
458
+ break
459
+
460
+ sock.close()
461
+
462
+ def _handle(self, client):
463
+ while self.running:
464
+ try:
465
+ packet = _recv_packet(client)
466
+
467
+ if packet is None:
468
+ break
469
+
470
+ # Atualiza os estados do HOST
471
+ _apply_packet(packet)
472
+
473
+ # Repassa aos outros clientes
474
+ self._broadcast(packet, exclude=client)
475
+
476
+ except:
477
+ break
478
+
479
+ with self.lock:
480
+ if client in self.clients:
481
+ self.clients.remove(client)
482
+
483
+ try:
484
+ client.close()
485
+ except:
486
+ pass
487
+
488
+ def close(self):
489
+ global _server_instance
490
+
491
+ self.running = False
492
+
493
+ if _server_instance is self:
494
+ _server_instance = None
495
+
496
+ for sock in (self.tcp, self.udp):
497
+ if sock:
498
+ try:
499
+ sock.close()
500
+ except:
501
+ pass
502
+
503
+ with self.lock:
504
+ clients = list(self.clients)
505
+ self.clients.clear()
506
+
507
+ for client in clients:
508
+ try:
509
+ client.close()
510
+ except:
511
+ pass
512
+
513
+
514
+ def host(port):
515
+ return Server(port)
@@ -0,0 +1,219 @@
1
+ Metadata-Version: 2.4
2
+ Name: wifi-server
3
+ Version: 1.0.0
4
+ Summary: Simple LAN communication for Python multiplayer projects
5
+ Author: Aquilesinho
6
+ License: MIT
7
+ Keywords: multiplayer,network,lan,pygame
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Operating System :: OS Independent
10
+ Requires-Python: >=3.9
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Dynamic: license-file
14
+
15
+ # wifi-server
16
+
17
+ Biblioteca Python para comunicação multiplayer simples entre computadores na mesma rede local (LAN), usando descoberta UDP e comunicação TCP.
18
+
19
+ > Projeto inicial baseado no código fornecido. A API e os exemplos abaixo descrevem o comportamento implementado nesta versão.
20
+
21
+ ## Instalação
22
+
23
+ ```bash
24
+ pip install wifi-server
25
+ ```
26
+
27
+ ## Importação
28
+
29
+ ```python
30
+ import wifi
31
+ ```
32
+
33
+ ## Visão geral
34
+
35
+ - `wifi.host(port)`: cria um servidor.
36
+ - `server.on()`: inicia o servidor.
37
+ - `wifi.connect(port)`: procura e conecta ao servidor na rede local.
38
+ - `wifi.send(value, name)`: envia/atualiza um valor associado a um nome.
39
+ - `wifi.get(name, default=None)`: lê o último valor recebido/armazenado.
40
+ - `wifi.on(name, callback)`: registra callback para atualizações.
41
+ - `wifi.remove(name)`: remove um valor compartilhado.
42
+ - `wifi.reset()`: limpa todos os valores compartilhados.
43
+ - `wifi.close()` ou `server.close()`: encerra a conexão ou servidor.
44
+
45
+ ## Criando um servidor (Host)
46
+
47
+ ```python
48
+ import wifi
49
+
50
+ server = wifi.host(1234)
51
+ server.on()
52
+
53
+ # O servidor também pode enviar dados:
54
+ wifi.send("Olá!", "mensagem")
55
+ ```
56
+
57
+ `wifi.host(port)` cria e retorna uma instância de `Server`. `server.on()` inicia os serviços de descoberta UDP e conexão TCP em threads de fundo e retorna a própria instância.
58
+
59
+ ## Conectando como Client
60
+
61
+ ```python
62
+ import wifi
63
+
64
+ wifi.connect(1234)
65
+ wifi.send("Olá, Host!", "mensagem")
66
+ ```
67
+
68
+ `wifi.connect(port)` envia uma solicitação de descoberta UDP por broadcast e tenta conectar ao servidor encontrado na mesma porta. Se não encontrar o servidor, gera `ConnectionError`.
69
+
70
+ ## Enviando dados
71
+
72
+ ```python
73
+ wifi.send(valor, nome)
74
+ ```
75
+
76
+ Associado a um nome, o valor é enviado e armazenado no estado compartilhado.
77
+
78
+ Tipos suportados pelo código atual:
79
+
80
+ - `bool`
81
+ - `int`
82
+ - `float`
83
+ - `str`
84
+ - `bytes`
85
+ - `list`
86
+ - `tuple` (serializado como JSON; ao receber, é decodificado como lista)
87
+
88
+ Exemplos:
89
+
90
+ ```python
91
+ wifi.send(100, "pontuação")
92
+ wifi.send(3.14, "velocidade")
93
+ wifi.send(True, "pronto")
94
+ wifi.send("Olá", "texto")
95
+ wifi.send(b"\x00\x01", "bytes")
96
+ wifi.send([10, 20], "posição")
97
+ wifi.send((10, 20), "posição_tupla")
98
+ ```
99
+
100
+ Tipos não suportados geram `TypeError`.
101
+
102
+ ## Recebendo / consultando dados
103
+
104
+ ```python
105
+ valor = wifi.get("posição")
106
+ ```
107
+
108
+ `wifi.get(name, default=None)` retorna o valor mais recente armazenado para o nome ou `default` se o nome não existir.
109
+
110
+ ```python
111
+ posição = wifi.get("posição", [0, 0])
112
+ ```
113
+
114
+ ## Callbacks
115
+
116
+ ```python
117
+ def ao_receber(valor):
118
+ print("Atualização:", valor)
119
+
120
+ wifi.on("posição", ao_receber)
121
+ ```
122
+
123
+ `wifi.on(name, callback)` registra uma função que será chamada quando aquele nome for atualizado por um pacote recebido ou aplicado localmente. O callback recebe o valor como único argumento.
124
+
125
+ ## Remover um valor
126
+
127
+ ```python
128
+ wifi.remove("posição")
129
+ ```
130
+
131
+ `wifi.remove(name)` remove o nome do estado compartilhado e envia o comando de remoção aos outros participantes.
132
+
133
+ ## Limpar todos os valores
134
+
135
+ ```python
136
+ wifi.reset()
137
+ ```
138
+
139
+ `wifi.reset()` limpa o estado compartilhado inteiro e envia o comando de reset.
140
+
141
+ ## Encerrar um Client
142
+
143
+ ```python
144
+ wifi.close()
145
+ ```
146
+
147
+ `wifi.close()` encerra o socket do cliente e interrompe o loop de recebimento.
148
+
149
+ ## Encerrar um Host
150
+
151
+ ```python
152
+ server.close()
153
+ ```
154
+
155
+ `Server.close()` encerra os sockets do servidor, fecha os clientes conectados e interrompe os serviços.
156
+
157
+ ## API de Host
158
+
159
+ ### `wifi.host(port)`
160
+
161
+ Cria uma instância de `Server` para a porta informada.
162
+
163
+ ### `server.on()`
164
+
165
+ Inicia o Host. Retorna `server`, permitindo encadeamento:
166
+
167
+ ```python
168
+ wifi.host(1234).on()
169
+ ```
170
+
171
+ ### `server.close()`
172
+
173
+ Fecha o servidor e os clientes conectados.
174
+
175
+ ## Exemplo: posição de jogador
176
+
177
+ Host:
178
+
179
+ ```python
180
+ import wifi
181
+
182
+ server = wifi.host(1234)
183
+ server.on()
184
+
185
+ wifi.send([100, 200], "Player1Pos")
186
+ ```
187
+
188
+ Client:
189
+
190
+ ```python
191
+ import wifi
192
+
193
+ wifi.connect(1234)
194
+
195
+ posição = wifi.get("Player1Pos", [0, 0])
196
+ ```
197
+
198
+ ## Arquivos `.wifi`
199
+
200
+ Ao iniciar o Host, a biblioteca cria ou verifica um arquivo de identificação em:
201
+
202
+ `%LOCALAPPDATA%\Aquilesinho\wifi\<porta>.wifi`
203
+
204
+ O arquivo contém uma assinatura e a porta do Host.
205
+
206
+ ## Observações e limitações desta versão
207
+
208
+ - A descoberta é feita por broadcast UDP, portanto a rede e o firewall precisam permitir a comunicação.
209
+ - O sistema foi projetado para uso em rede local.
210
+ - O estado é armazenado em memória; não é um banco de dados persistente.
211
+ - Os callbacks executam no contexto da thread que recebe/aplica o pacote. Se usar Pygame, considere apenas guardar os dados no callback e processá-los no loop principal.
212
+ - A implementação atual não fornece autenticação nem criptografia. Não envie informações sensíveis.
213
+ - `wifi.connect(port)` usa timeout de 3 segundos na descoberta UDP.
214
+ - `wifi.send()` não retorna confirmação de entrega.
215
+ - O servidor repassa as atualizações recebidas para os demais clientes e também aplica as atualizações ao estado local.
216
+
217
+ ## Licença
218
+
219
+ MIT.
@@ -0,0 +1,9 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ wifi/__init__.py
5
+ wifi/main.py
6
+ wifi_server.egg-info/PKG-INFO
7
+ wifi_server.egg-info/SOURCES.txt
8
+ wifi_server.egg-info/dependency_links.txt
9
+ wifi_server.egg-info/top_level.txt