0

Here I am confused to initialize the socket when the instance is initialized, and I use it to transfer data through it in a loop.

class Server2:
    host = "localhost"
    port = 44444
    s = ""
    sock = ""
    addr = ""


    def __init__(self,voitingSistem,voitingInterfece,voiting,sql):
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.s.bind((self.host, self.port))
        self.s.listen(5)
        self.sock, self.addr =self.s.accept()
        self.client = WorkWithClient()
        self.voitingSistem = voitingSistem()
        self.voitingInterfece = voitingInterfece()
        self.voiting = Voiting("d")
        super().__init__()

     def mainLoop(self):
         while True:
             buf = self.sock.recv(1024) # receive and decode a command
             print("getting command: "+(buf.decode('utf8')))
             ansver = self.client.AcceptCommand(buf.decode('utf8')) # act upon the command

             if buf.decode('utf8') == "exit":
                 self.sock.send("bye")
                 break
             elif buf:
                 self.sock.send(buf)
                 print(buf.decode('utf8'))
                 self.sock.close()

Error:

An attempt was made to perform an operation on an object that is not a socket

3
  • 1
    Which line did this happen? Commented Jul 30, 2017 at 16:02
  • The program receives the first data. But the next bit of data crashes with such a mistake. Commented Jul 30, 2017 at 16:53
  • Please indent your code correctly in the paste. (4 spaces missing before mainLoop). Also it will take the whole stacktrace to help you. Commented Jul 31, 2017 at 0:10

1 Answer 1

1

The following condition is always true and the code will always be executed unless buf is equal to exit:

elif buf:
    self.sock.send(buf)
    print(buf.decode('utf8'))
    self.sock.close()

Earlier in the code you obtain buf by calling self.sock.recv(1024). For a usual socket in blocking mode it will return at least one byte. There are no circumstances under which buf will be empty. Program execution will be simply blocked until some data arrives. If something really bad happens, like disconnect, you'll be notified by an exception, not by receiving an empty buffer.

So essentially you close a connection to a client after the first chunk of data is received. I believe you meant to have self.sock.close() in == 'exit' section.

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.