I am trying to implement a socket server that listens to a particular port number. When I write the code without any class, it works fine. But fails to work when I implement the class as below:
import socket;
from ServerConfig import ServerConfig;
class SyncServerRK:
def __init__(self):
self.config = ServerConfig() #Call Initialize config class
#Send my IP address to managing_agent
self.Listener() #Call listener method
def Listener(self):
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = self.config.Connect_Port() # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
while True:
c, addr = s.accept() # Establish connection with client.
print ('Got connection from', addr)
c.send('Thank you for connecting'.encode())
print ('Message received:',c.recv(1024).decode())
c.close() # Close the connection
print(self.config.Managing_Agent())
if __name__ == "__main__":
SyncServerRK()
The error I received is:
Traceback (most recent call last):
File "C:/Share/SyncServerRK.py", line 24, in <module>
SyncServerRK()
File "C:/Share/SyncServerRK.py", line 8, in __init__
self.Listener() #Call listener method
File "C:/Share/SyncServerRK.py", line 16, in Listener
c, addr = s.accept() # Establish connection with client.
File "C:\Python33\lib\socket.py", line 135, in accept
fd, addr = self._accept()
OSError: [WinError 10022] An invalid argument was supplied
Can someone please advise how to implement a server socket with threads using object-oriented philosophy.
The Non class version that worked well:
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print ('Got connection from', addr)
c.send('Thank you for connecting'.encode())
print ('Message received:',c.recv(1024).decode())
c.close() # Close the connection
You are missing the
s.listen(5)in your class based version.The socket must be bound to an address and listening for connections before accepting connections.