Search code examples
pythonpython-3.xsockets

Type Error when trying to socket due to python reading host as a tuple


Ight, so im a complete novice when it comes to python, so try not to laugh when you see my code. Im trying to make a simple socketing server and client where i can send some data from the client to the server and have it send it back. Here it is:

Server:

import socket
def Main():
    print("--------------------------------------------------------------------------------")
    print("Please input host. If field left blank, host is localhost")
    host = input()
    if host == "":
        host = "127.0.0.1"
    print("Please input port. Now that i think about it, don't, unless told to, just leave it as is (Blank)")
    port = input()
    if port == "":
        port = 5000
    print("--------------------------------------------------------------------------------")
    #############################################################################################################################################

    s = socket.socket()
    s.bind((host,port))

    s.listen(1)
    c, addr = s.accept()
    print("Connecton from: " + str(addr))
    while True:
        data = c.recv(1024).decode("utf-8")
        if not data:
            break
        print("From connected user: " + data)
        data = data * 2 #This is just to test if it works, by doubing it
        print("Sending: " + data)
        c.send(data.encode("utf-8"))
    s.close


if __name__ == "__main__":
    Main()

Right, so here is my client:

import socket

def Main():
    host = '127.0.0.1'
    port = 5000

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

    message = input("-> ")
    while message != "quit":
        s.send(message.encode("utf-8"))
        data = s.recv(1024).decode("utf-8")
        print("Recicved from server: "+ data)
        message = input("-> ")
    s.close()




if __name__ == "__main__":
    Main()

Ya see, if i try to run the client, i get a Type Error:

Traceback (most recent call last):
  File "C:/Users/Napoleon/Desktop/Szymon/Python/Client.py", line 34, in <module>
    Main()
  File "C:/Users/Napoleon/Desktop/Szymon/Python/Client.py", line 20, in Main
    s.connect((host,port))
TypeError: descriptor 'connect' requires a '_socket.socket' object but received a 'tuple'

So could any of you help me figure out what is going on wiht my code. Thanks in advance! :)


Solution

  • s = socket.socket
    

    is aliasing the class socket, so s.connect won't work, you need an instance of the socket object:

    s = socket.socket()
    

    (I must admit the error is not very easy to understand)