在使用Python脚本来提供xml文件时,遇到了一个问题: 无法在指定的端口上提供xml文件。以下是问题的详细信息:
- 脚本无法在端口843上提供flashpolicy.xml文件。
- 脚本中的socket.error错误表明无法处理连接。
- 代码无法正确地启动服务。
2、解决方案
要解决这个问题,可以尝试以下步骤:
- 检查脚本的代码是否正确。
- 请确保flashpolicy.xml文件位于脚本所在的同一文件夹中。
- 查看是否其他的程序或端口占用了843端口。
- 尝试修改端口号。
- 尝试使用其他编程语言重写脚本。
代码例子
import socket
import sys
import optparse
class AppServerSvc():
def __init__(self,args):
self.port = int(args[0])
self.path = args[1]
self.policy = self.read_policy(self.path)
print "Listening on port %d" % self.port
try:
self.sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
except AttributeError:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind(('', self.port))
self.sock.listen(5)
def read_policy(self, path):
with file(path, 'rb') as f:
policy = f.read(10001)
if len(policy) > 10000:
raise exceptions.RuntimeError('File probably too large to be a policy file',
path)
if 'cross-domain-policy' not in policy:
raise exceptions.RuntimeError('Not a valid policy file',
path)
return policy
def run(self):
try:
while True:
thread.start_new_thread(self.handle, self.sock.accept())
except socket.error, e:
print 'Error accepting connection: %s' % (e[1],)
def handle(self, conn, addr):
addrstr = '%s:%s' % (addr[0],addr[1])
try:
print 'Connection from %s' % (addrstr,)
with contextlib.closing(conn):
# It's possible that we won't get the entire request in
# a single recv, but very unlikely.
request = conn.recv(1024).strip()
if request != '<policy-file-request/>\0':
print 'Unrecognized request from %s: %s' % (addrstr, request)
return
print 'Valid request received from %s' % (addrstr,)
conn.sendall(self.policy)
print 'Sent policy file to %s' % (addrstr,)
except socket.error, e:
print 'Error handling connection from %s: %s' % (addrstr, e[1])
except Exception, e:
print 'Error handling connection from %s: %s' % (addrstr, e[1])
if __name__ == '__main__':
parser = optparse.OptionParser(usage = '%prog [--port=PORT] [--file=FILE]')
parser.add_option('-p', '--port', dest='port', type=int, default=843,
help='listen on port PORT', metavar='PORT')
parser.add_option('-f', '--file', dest='path', type="string", default="flashpolicy.xml",
help='something FILE', metavar='FILE')
opts, args = parser.parse_args()
if len(args) != 2:
parser.error('No arguments are needed. See help.')
if not opts.path:
parser.error('File must be specified. See help.')
AppServerSvc(args).run()
这是一个使用Python编写的服务端脚本,可以用来提供xml文件。这个脚本需要两个参数:端口号和xml文件的路径。脚本会监听指定的端口,当有客户端连接时,会发送xml文件给客户端。