Lojas
Lojas

Reputation: 205

Why doesn't my python socket connect to another computer?

So i've recently started testing out sockets and i have managed to create a server and client, which are both working together when i run them on the same pc. However, when i put in the server on a diffrent computer it gives me the following error: ""TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond""

Here is my server:

import socket
import pyautogui
import os

computerIP = socket.gethostbyname(socket.gethostname())

def Main():
    host = computerIP
    port = 5000
    value = 0
    mySocket = socket.socket()
    mySocket.bind((host,port))

    mySocket.listen(1)
    conn, addr = mySocket.accept()
    print ("Connection from: " + str(addr))
    while True:
            data = conn.recv(1024).decode()
            if not data:
                    break
            elif data == "shift":
                pyautogui.keyDown("shift")
            elif data == "relshift":
                pyautogui.keyUp("shift")
            elif data == "logout":
                os.popen("shutdown -l")
            elif data == "click":
                pyautogui.click()
                pyautogui.click()                                
            print ("from connected  user: " + str(data))
            data = str(data).upper()
            print ("sending: " + str(data))
            conn.send(data.encode())

    conn.close()

if __name__ == '__main__':
    Main()

My client:

import socket


def Main():
        host = #same ip as server
        port = 5000

        mySocket = socket.socket()
        mySocket.connect((host,port))

        message = input(" -> ")

        while message != 'q':
                mySocket.send(message.encode())
                data = mySocket.recv(1024).decode()

                print ('Received from server: ' + data)

                message = input(" -> ")

        mySocket.close()

if __name__ == '__main__':
    Main()

OS: Windows 8.1 Python verion: 3.4

I tried looking this up on the internet but since i'm pretty new to python i didn't understand much.

Tell me if there is anything i need to clearify.

Upvotes: 2

Views: 4942

Answers (1)

Vikas Tiwari
Vikas Tiwari

Reputation: 537

Looks like the port is blocked due to some firewall.

Use socket.connect_ex() instead of socket.connect(). If the connection succeeds it would return 0, otherwise the value of the errno variable will help you debug why the connection failed.

Prior to the connection also use socket.settimeout() so that the connection times out in the given no. of seconds.

Upvotes: 2

Related Questions