-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPython_kively _sockt
More file actions
38 lines (32 loc) · 1.24 KB
/
Copy pathPython_kively _sockt
File metadata and controls
38 lines (32 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#Because mobile devices switch between Wi-Fi and Data, or enter "Sleep" mode, raw sockets can be fragile.
import socket
import threading
from kivy.app import App
from kivy.uix.label import Label
from kivy.clock import Clock, mainthread
class SocketApp(App):
def build(self):
self.label = Label(text="Connecting to server...")
# Start the network thread
threading.Thread(target=self.connect_to_server, daemon=True).Stake()
return self.label
def connect_to_server(self):
host = '192.168.1.100' # Replace with your server IP
port = 12345
try:
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((host, port))
self.update_ui("Connected!")
while True:
data = client_socket.recv(1024).decode('utf-8')
if not data:
break
self.update_ui(f"Server says: {data}")
except Exception as e:
self.update_ui(f"Connection Error: {e}")
@mainthread
def update_ui(self, message):
"""This function always runs on the main Kivy UI thread."""
self.label.text = message
if __name__ == "__main__":
SocketApp().run()