2012-11-11 33 views
0

我想实现一个套接字服务器,侦听特定的端口号。当我编写没有任何类的代码时,它工作正常。但是失败的时候我实现类,如下工作:问题访问成员

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  
+0

http://docs.python.org/2/library/socketserver.html有各种套接字服务器的示例 - 线程,分叉,异步 – xbonez

+0

请也发布适用于您的非基于类的版本。 – gecco

+0

@gecco发布通过编辑问题工作的非基于类的版本。谢谢 – Romaan

回答

1

你缺少在基于类版本的s.listen(5)。 在接受连接之前,必须将套接字绑定到地址并监听连接。

+0

宾果...谢谢@gecco。非常愚蠢的我:(再次感谢 – Romaan