用Python服务器实现Flash套接字
我正在尝试通过套接字在Adobe Flash客户端和Python服务器之间发送和接收数据。
Flash客户端的代码如下:
var serverURL = "se.rv.er.ip";
var xmlSocket:XMLSocket = new XMLSocket();
xmlSocket.connect(serverURL, 50007);
xmlSocket.addEventListener(DataEvent.DATA, onIncomingData);
function onIncomingData(event:DataEvent):void
{
trace("[" + event.type + "] " + event.data);
}
xmlSocket.send("Hello World");
而Python服务器的代码是:
import socket
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if (data):
print 'Received', repr(data)
# data
if(str(repr(data)).find('<policy-file-request/>')!=-1):
print 'received policy'
conn.send('<?xml version="1.0"?><cross-domain-policy><allow-access-from domain="*" to-ports="50007" /></cross-domain-policy>')
conn.send('hellow wolrd')
conn.close()
但是这段代码没有正常工作。
Python服务器的输出结果是:
Connected by ('cl.ie.nt.ip', 3854)
Received '<policy-file-request/>\x00'
received policy
1 个回答
1
如果没有必要的话,你就不要使用socket模块。想要搭建一个socket服务器的话,应该使用SocketServer。
import SocketServer
class MyTCPHandler(SocketServer.BaseRequestHandler):
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print "%s wrote:" % self.client_address[0]
print self.data
if '<policy-file-request/>' in self.data:
print 'received policy'
conn.send('<?xml version="1.0"?><cross-domain-policy><allow-access-from domain="*" to-ports="50007" /></cross-domain-policy>')
conn.send('hellow wolrd')
def main():
# Create the server, binding to localhost on port 9999
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
它应该这样工作……