Home > Enterprise >  OSError: [Errno 22] Invalid argument python socket connection problem
OSError: [Errno 22] Invalid argument python socket connection problem

Time:06-20

Currently am creating TCP socket to send and receive data for a backend app but am facing self.socket.connect(("localhost", 8000)) OSError: [Errno 22] Invalid argument error... have looked up similar errors on here along with other forums and has something to do with me placing self.socket.connect(("localhost", 8000)) within the other indented code in the start_client function but when I try to place it elsewhere within the file I'm either getting self is not defined or invalid argument for socket_connect

Here's my ClientServer.py code:

import socket
from threading import Thread

MAX_BUFFER_SIZE = 4096

class ClientServer(Thread):

    def __init__(self):
        print("Client Server started w/ new threads...")
        Thread.__init__(self)
        self.socket = None

    def send_to_Server(self, data):
        print('Time to send data to Server..... %s', data)
        self.socket.send(data.encode("utf8"))   

    def receive_from_Server(self):
        print('Time to receive from Server.....')
        result_bytes = self.socket.recv(MAX_BUFFER_SIZE)
        result_string = result_bytes.decode("utf8")
        print("Result from server is {}".format(result_string))

    def start_client(self):
        # Creates TCP socket
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # Re-uses socket
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        # Binds socket to host and port
        self.socket.bind(("localhost", 8000))
        # Connects socket to host and port
        self.socket.connect(("localhost", 8000))
        print('Client connected....')
        threads = [] 


    def connect_client(self):
        
        while True:
            # Become a server socket
            self.socket.listen(5)
            self.__clients = {}

            # Starts connection
            (clientSocket, client_address) = self.socket.accept()
            newthread = ClientServer("localhost", 8000)
            newthread.start
            threads.append(newthread)

            for t in threads:
                t.join()


            

cs = ClientServer()

cs.start_client()
cs.connect_client()
cs.send_to_Server('Hello')
cs.receive_from_Server()

CodePudding user response:

socket.bind is used by a server to start offering services. socket connect is used by the client. If this is just supposed to be the client, then delete the bind call. Check the chart here:

socket connect() vs bind()

In that case, your class name is probably not appropriate.

  • Related