Search code examples
pythonsocketstcpglobalattributeerror

Python Use Socket as Global Variable


I have created a function that establishes the TCP/IP socket connection to the server. Now I would like to reuse the socket for other tasks in my application. So that I have:

import socket

def creat_tcp_connection():
    sock_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock_tcp.connect(("163.173.96.12", 32000))
    return sock_tcp

if __name__ == "__main__":
    creat_tcp_connection()
    texte = "PING\n"
    creat_tcp_connection.sock_tcp.send(texte.encode('utf-8'))
    data=creat_tcp_connection.sock_tcp.recv(1024).decode('utf-8')
    print("Received ", str(data))

But "AttributeError: 'function' object has no attribute 'sock_tcp'". How can use the socket sock_tcp inside the creat_tcp_connection() function

Thank you very much!


Solution

  • You are trying to access attributes of the function, not the return value of the function. Try this:

    import socket
    
    def creat_tcp_connection():
        sock_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock_tcp.connect(("163.173.96.12", 32000))
        return sock_tcp
    
    if __name__ == "__main__":
        sock = creat_tcp_connection()
        texte = "PING\n"
        sock.send(texte.encode('utf-8'))
        data=sock.recv(1024).decode('utf-8')
        print("Received ", str(data))