Home > Mobile >  problem in creating a different thread for socket in kivy framework
problem in creating a different thread for socket in kivy framework

Time:02-08

I'm using kivy framework and socket.in the call back back function this code conn, addr=s.accept() makes problems for kivy and stops its work.that's mean when i'm clicking start server button kivy gui is not responding.I tried to create a thread and i used : Thread(target=s.listen()).start() but is this thread work different from kivy? what should i do to kivy be responsive with socket?


code:

import kivy
from threading import Thread
import socket
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.clock import Clock



    
s=socket.socket()
s.bind(('localhost',1234))
Thread(target=s.listen()).start()
print('listen')


class me (App):
    def __init__(self):
        super().__init__()
        
        self.b=Button(text='start server',on_press=self.callback)
        self.g=GridLayout(cols=4)
        self.l=Label(text='listening...')
        self.t=TextInput(hint_text='Type here your message: ' )
        self.g.add_widget(self.b)
        self.g.add_widget(self.t)
        self.g.add_widget(self.l) 
    def build(self):
            return self.g
        
    def callback(self,click):
        conn, addr=s.accept()



m=me()


m.run()

CodePudding user response:

Try this:

from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.app import App



import socket
from threading import Thread


class Me(App):
    def __init__(self):
        super().__init__()

        self.b = Button(text='start server', on_press=self.callback)
        self.g = GridLayout(cols=4)
        self.l = Label(text='listening...')
        self.t = TextInput(hint_text='Type here your message: ')
        self.g.add_widget(self.b)
        self.g.add_widget(self.t)
        self.g.add_widget(self.l)

    def build(self):
        return self.g


    def stream(self):
        while True:
            conn, addr = self.sock.accept()
            print(addr)
            conn.send(self.t.text.encode())
            print(f"{self.t.text} sended!")
            conn.close()

    def callback(self, click):
        self.sock = socket.socket()
        self.sock.bind(('localhost', 1234))
        self.sock.listen(1000)
        Thread(target=self.stream).start()
        print("server started")


m = Me()
m.run()
  •  Tags:  
  • Related