0

I'm very new to programing and I've just started trying to open socket so don't be hard on me. I'm trying to make a class for my socket functions but when I run the client function it just wont work if I have the "self.sock.connect((host, port))" inside the client function. So I made another function and then just called it from the client function. But the problem still remains for the host function. I keep getting this error message (down). What am I doing wrong? When should you use self ? (PS: I've done this before without making it to a class, then it worked.)

>>> SC.host()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "SocketClass.py", line 30, in host
    self.sock.listen(1)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 22] Invalid argument

the code:

 import socket

    class SocketConnect():

        def __init__(self):
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        #def socketSetup(self, host, port):
            #self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            #self.sock.connect((host, port))

        def client(self, host, port):
            self.sock.connect((host, port))
            while True:
                x = raw_input("Vilken fil ska skickas? ")
                try:
                    fo = open(x, "rb")
                    data_to_send = fo.read()
                    self.sock.sendall(data_to_send)
                except:
                    print "***Filen kunde inte hittas***"

                self.sock.sendall(data_to_send)

            data = self.sock.recv(1024)
            self.sock.close()

        def host(self):
            self.sock.listen(1)
            conn, addr = self.sock.accept()

            print "Connected by: " + str(addr)

            while True:
                data = conn.recv(1024)
                file = open("pic.png", "wb")
                file.write(data)

            conn.close()
1
  • You need to bind the socket first Commented Sep 16, 2014 at 13:02

1 Answer 1

1

If you want to listen then you should specify to listen on what?

def host(self):
    self.sock.bind(('0.0.0.0', 1234))
    self.sock.listen(1)
    ...

Now the host will listen at port 1234 and accept connections from any ip.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.