Python中的套接字编程错误:“组参数现在必须为None”和“SocketErr Errno。111”
问题描述:
我正在尝试使用Python实现套接字编程。Python中的套接字编程错误:“组参数现在必须为None”和“SocketErr Errno。111”
server.py
import socket
from threading import Thread
try:
from SocketServer import ThreadingMixIn, ForkingMixIn
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
except ImportError:
from socketserver import ThreadingMixIn, ForkingMixIn
from http.server import HTTPServer, BaseHTTPRequestHandler
#from SocketServer import ThreadingMIxIn
class ClientThread(Thread):
def _init_(self,ip,port):
Thread._init_(self)
self.ip=ip
self.port= port
print ("[+] New server socket thread started for " + + ":" + str(port))
def run(self):
while True :
data = conn.recv(2048)
print ("Server received data:", data)
MESSAGE = raw_input("Multithreaded Python Server : Enter response from sever Enter exit:")
if MESSAGE == 'exit' :
#break
conn.send(MESSAGE)
TCP_IP ='0.0.0.0'
TCP_PORT = 2024
BUFFER_SIZE = 20
tcpServer = socket.socket()
tcpServer.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
tcpServer.bind((TCP_IP,TCP_PORT))
threads=[]
while True:
tcpServer.listen(4)
print ("Multithreaded python server: Waiting for connections from tcp clients...")
(conn ,(ip,port)) = tcpServer.accept()
newthread=ClientThread(ip,port)
newthread.start()
threads.append(newthread)
for t in threads:
t.join() #end
client.py
import socket
host=socket.gethostname()
port=2024
BUFFER_SIZE= 2000
MESSAGE = raw_input("tcpClientB: Enter message/Enter exit:")
tcpClientB =socket.socket()
tcpClientB.connect((host, port))
while MESSAGE !='exit':
tcpClientB.send(MESSAGE)
data=tcpClientB.recv(BUFFER_SIZE)
print ("Client received data",data)
MESSAGE=raw_input("tcpClientB: Enter message to continue/ Enter exit:")
tcpClientB.close()
当我试图运行这一点,首先server.py
然后client.py
,我得到这个错误server.py
Multithreaded python server: Waiting for connections from tcp clients...
Traceback (most recent call last):
File "mserver.py", line 47, in <module>
newthread=ClientThread(ip,port)
File "/usr/lib/python2.7/threading.py", line 670, in __init__
assert group is None, "group argument must be None for now"
AssertionError: group argument must be None for now
,并从client.py
以下错误:
python client2.py
tcpClientB: Enter message/Enter exit:exit
Traceback (most recent call last):
File "mclient2.py", line 10, in <module>
tcpClientB.connect((host, port))
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused
我不明白我在做什么错。当我在运行后输入exit
后,它给我SocketErr Errno. 111
。
答
errno 111表示'连接被拒绝'。服务器拒绝连接,因为它由于Thread构造函数调用中的错误而崩溃。 Python中的构造函数是__init__
(双重双下划线)。
你的程序只是定义了一个方法init而不是构造函数,Thread构造函数的第一个参数是一个组。
服务器更改为
def __init__(self,ip,port):
Thread.__init__(self)
'_init_' - >'__init__' –