访问会员中的问题

时间:2012-11-11 07:54:51

标签: python

我正在尝试实现一个侦听特定端口号的套接字服务器。当我编写没有任何类的代码时,它工作正常。但是当我按如下方式实现类时无法工作:

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()

我收到的错误是:

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

有人可以建议如何使用面向对象的哲学实现带有线程的服务器套接字。

运行良好的非类版本:

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      

1 个答案:

答案 0 :(得分:2)

您在基于班级的版本中遗漏了s.listen(5)。 在接受连接之前,套接字必须绑定到一个地址并侦听连接。