這是我玩過的代碼,但每次我犯了一個錯誤,我都無法重新啓動它。 它對我說,端口/插座已被使用 這是第一個問題 第二個是在我的MyTCPHandler我怎麼知道使用的端口? 這裏是我的代碼:python SocketServer.BaseRequestHandler知道端口並使用已經打開的端口
# MetaProject v 0.2
# -*- coding: utf-8 -*-
"""
Thanks to :
People from irc :
Flox,Luyt
People from stack Overflow :
Philippe Leybaert,Platinum Azure,methodin,Suresh Kumar,S.Lott,MatTheCat,
kevpie,Ignacio Vazquez-Abrams,adamk,Frédéric Hamidi,THC4k,THC4k,Blam
"""
import SocketServer
import threading
class MyTCPHandler(SocketServer.BaseRequestHandler):
def handle(self):
self.data = self.request.recv(1024)
socket = self.request
print "%s wrote:" % self.client_address[0]
print self.data
print self.__dict__
socket.sendto(self.data.upper(), self.client_address)
def serve_thread(host, port):
server = SocketServer.TCPServer((host, port), MyTCPHandler)
server.serve_forever()
if __name__ == "__main__":
threading.Thread(target=serve_thread,args=('localhost', 1238)).start()
threading.Thread(target=serve_thread,args=('localhost', 1237)).start()
print "toto"
我所做的:
def serve_thread(host, port):
if port == 1858 :
server = SocketServer.TCPServer((host, port), Serverhttp,bind_and_activate=True)
elif port == 1958 :
server = SocketServer.TCPServer((host, port), Serversmtp,bind_and_activate=True)
server.allow_reuse_address=True
server.serve_forever()
,但它不工作。 Regards
請問您能更具體些嗎? – user462794 2010-10-12 06:00:11
請問你能更具體些嗎?我可以這樣做:def serve_thread(host,port): if port == 1858: server = SocketServer.TCPServer((host,port),Serverhttp,bind_and_activate = True) elif port == 1958: server = SocketServer。 TCPServer((主機,端口),Serversmtp,bind_and_activate = True) server.allow_reuse_address = True server.serve_forever() – user462794 2010-10-12 06:21:10
@ user462794:什麼不起作用?您已將此答案標記爲已接受,請讓我知道您是否仍遇到問題。 – bstpierre 2010-10-12 11:31:54