由于是Python的新手,我正在关注一个示例,以获得简单的TCP连接。以下代码是服务器部分,但我想添加自己的构造函数,该构造函数接受其他值,例如名称和可能的ID。
服务器如下:
#!/usr/bin/env python
import SocketServer
class MyTCPServer(SocketServer.ThreadingTCPServer):
allow_reuse_address = True
class MyTCPServerHandler(SocketServer.BaseRequestHandler):
def handle(self):
while 1:
try:
data = self.request.recv(1024).strip()
except Exception, e:
print "Error getting message. ", e
if data:
print data
server = MyTCPServer(('192.168.1.103', 13373), MyTCPServerHandler)
server.serve_forever()
客户端代码是:
#!/usr/bin/env python
import socket
import json
hostname = '192.168.1.103'
port = 13373
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((hostname,port))
except Exception, e:
print "Error, could not open socket: ", e
sock.send("HI")
在我的服务器中,我尝试添加def __init__(self, name, id)
,但这似乎不起作用。当我创建一个新服务器
server = MyTCPServer(('192.168.1.103', 13373), MyTCPServerHandler)
我也想传递一个名字和ID。
阅读SocketServer.ThreadingTCPServer的文档,它说
__init__(self, server_address, RequestHandlerClass)
(Constructor)
Constructor. May be extended, do not override.
答案 0 :(得分:1)
我认为它可以帮助您理解概念
class A(object):
def __init__(self):
print "entering A"
super(A, self).__init__()
print "leaving A"
class B(object):
def __init__(self):
print "entering B"
super(B, self).__init__()
print "leaving B"
class C(A,B):
def __init__(self):
print "entering c"
A.__init__(self)
B.__init__(self)
print "leaving c"