我正在尝试使用Python实现套接字编程。
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
。
答案 0 :(得分:1)
错误111表示“拒绝连接”。服务器拒绝连接,因为它由于Thread构造函数调用中的错误而崩溃。 python中的构造函数是__init__
(双双下划线)。
您的程序只定义了一个方法 init 而不是构造函数,而Thread构造函数的第一个参数是一个组。
将您的服务器更改为
def __init__(self,ip,port):
Thread.__init__(self)