开发者

Why my program freezing while I am listening socket

So, here is some code:

obj.HOST = ""
obj.PORT = int(port.get()) # it's 100% correct PORT number
obj.srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
obj.srv.bind((obj.HOST, obj.PORT))
obj.srv.listen(1)
obj.sock, obj.addr = obj.开发者_如何学Gosrv.accept()

class Client(threading.Thread):
     def __init__(self,from_):
        if from_.ip.get() == '':
            obj.HOST = 'localhost' # I am starting both programs from 1 computer, so it's 'localhost'
        else:
            obj.HOST = from_.ip.get()
        obj.PORT = int(from_.port.get()) # it's 100% correct PORT number (the same as previous)
        obj.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        obj.sock.connect((obj.HOST, obj.PORT))
        threading.Thread.__init__(self)
     def run(self):
        command = obj.sock.recv(1024)
        print command
        if command == 'confirm':
            print 'confirm'
        elif command == 'start':
            print 'start'

client = Client(cl) # cl is class, where I get port. It's works 100% correct
client.start()

I start the same program on my computer. One is host, second is client.

Question 1: while I'm waiting to connect, my server script is freezing. How it repair? After connection both programs work correctly, but when server send some information(string), client script freezing.

Question 2: so how it can be repaired?


Not sure what the obj is. But you are not sending anything from the server to client. on the server side, you could do some thing like this :

conn, addr = srv.accept()
print 'Connected by', addr
conn.send("confirm")
conn.close()

This will accept a single connection, send some data "confirm", close connection and exit.

Same with client side:

def run(self):
        command = self.sock.recv(1024)
        print command
        print "Recieved : ", command
        self.sock.close()

This will connect to server, receive some data, print and close connection.

recv is a blocking call and will block till it receives some data from the server. This might be the cause of your freeze up.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜