Mike
Mike

Reputation: 550

Issue With a Simple Server - Client Program

I run the following script:

import socket, threading, time,Queue
if __name__ == '__main__':
    pass

print("Starting...")

def server(): 
    s = socket.socket()
    host = socket.gethostname()
    port = 1247
    s.bind((host,port))
    s.listen(5)

    while True:
        c, addr = s.accept()
        print("Connection accepted from " + repr(addr[1]))
        c.send("Server approved connection\n")
        print (addr[1]) + ": " + c.recv(1026)
        c.close()

def client ():
    time.sleep(5)
    print("Client Started")
    s = socket.socket()
    host = socket.gethostname()
    port = 1247
    s.connect((host, port))
    print (s.recv(1024))
    inpt = raw_input('type anything and click enter... ')
    s.send(inpt)
    print ("the message has been sent")

q = Queue.Queue() 
t = threading.Thread(client(), args = (q))
t.daemon = True
t.start()  

server() 

I get this error:

Starting...
Client Started
return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused

Note that port 1247 is open in my device (Ubuntu OS).

Connection Refused means there is nothing to connect to. But What is wrong with the server, I cannot find the problem with it. Any help is very much appreciated after one week of tries!

Upvotes: 0

Views: 787

Answers (1)

sauerburger
sauerburger

Reputation: 5148

When you create the thread, you are accidentally starting the client. The first argument of threading.Thread is client(), which executes the client including the initial sleep. Which blocks the main thread. You should change this to

t = threading.Thread(target=client, args = (q,))

The target argument expects a callable object, i.e. your client. Once you start the tread, it will execute the client on a different thread. Please note, the lack of () after client.

Upvotes: 0

Related Questions