如何从简单的 Python 服务器打印到 html 页面?
Posted
技术标签:
【中文标题】如何从简单的 Python 服务器打印到 html 页面?【英文标题】:How do I print to an html page from a simple Python Server? 【发布时间】:2013-11-25 21:52:09 【问题描述】:我正在使用这个简单的 Python 服务器 -> https://github.com/opiate/SimpleWebSocketServer。我编写了自己的版本,名为 server.py,它处理来自 iPhone 应用程序的请求。现在我只在我的 EC2/本地实例上打印到控制台(取决于我运行的内容),但我似乎无法打印到 html 以在浏览器中显示。
这是我的服务器代码:
#!/usr/bin/python
from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer
import time
import thread
import json
# time benchmarks
startTime = None
startFinishedSendingTime = None
endTime = None
# count of the number of data received; will be 2*n (where n is the number of devices)
# (because each device will send two points over the data socket: raw GPS data and then the calculated result)
dataReceived = 0
# whether we are performing distributed or local calculations
experimentType = ""
# collection of all final calculated results received from the client devices
resultsReceived = []
# used to make sure that we have the same number of connections over control and data sockets
numClientsControl = 0
numClientsData = 0
# a reference to the server (ourself)
server = None
# saveResults -- saves the experiment data to a file
# TODO: implementation
def saveResults():
global startTime
global startFinishedSendingTime
global endTime
global resultsReceived
print "--------------------------------------------------------"
print "-- RESULTS ---------------------------------------------"
print "--------------------------------------------------------"
print "Start Time: %s" % startTime
print "Start Time: %s" % startFinishedSendingTime
print "End Time: %s" % endTime
print "--------------------------------------------------------"
print "Locations:"
# loop over all locations
for data in resultsReceived:
print data
print "--------------------------------------------------------"
# reset -- resets startTime, endTime, dataReceived, experimentType, results received
def reset():
# the number of connected cliends will remain accurate
# we do not ever reset them
global experimentType
global resultsReceived
global dataReceived
global startTime
global endTime
global server
experimentType = ""
resultsReceived = []
dataReceived = 0
startTime = None
endTime = None
for conn in server.connections.itervalues():
conn.sendMessage(str("'command':'RESET'"))
# not used any more -- GOOD Example code
class SimpleEcho(WebSocket):
def handleMessage(self):
if self.data is None:
self.data = ''
print self.data
print self.server.connections
for conn in self.server.connections.itervalues():
conn.sendMessage(str(self.data))
def handleConnected(self):
print self.address, 'connected'
def handleClose(self):
print self.address, 'closed'
# logic for handling the control socket
class ControlSocket(WebSocket):
# handles an incoming message to the socket
def handleMessage(self):
global numClientsControl
global startTime
global server
server = self.server
if self.data is None:
self.data = ''
# get the data in JSON format
try:
data = json.loads(str(self.data))
print data
except Exception:
print "Exception"
# branch based on command
if data['command'] == 'START':
# start command received
# record the current time as the start of the experiment
startTime = time.time()
data['numClients'] = numClientsControl
print "%s Starting Experiment with %s devices" % (startTime, numClientsControl)
# forward the start message to all devices (including origin device) to signal them to snapshot data and perform their calculations
for conn in self.server.connections.itervalues():
conn.sendMessage(str(data))
# record the time after we've sent all data - we use this to benchmark communication speed
# TODO: check to see if sendMessage is synchronous or asynchronous (i.e. is it blocking until the data has sent or not; if it isn't blocking, this metric will be flawed)
startFinishedSendingTime = time.time()
def handleConnected(self):
global numClientsControl
print self.address, "Connected Control"
numClientsControl += 1
def handleClose(self):
global numClientsControl
global startTime
print self.address, "Closed Control"
numClientsControl -= 1
# deal with disconnect during experiment
if startTime is not None:
print "---ERROR---\nClient disconnected (control) mid-experiment\n-----------"
for conn in self.server.connections.itervalues():
conn.sendMessage("\"command\":\"RESET\"")
startTime = None
# logic for handling the data socket
class DataSocket(WebSocket):
def handleMessage(self):
global dataReceived
global resultsReceived
global startTime
global endTime
global numClientsData
if self.data is None:
self.data = ''
print "DATA MESSAGE ----------------------"
print self.data
# branch based on the data series we are expecting (either raw GPS to be forwarded to other devices or calculated results)
# out of 2*n messages that will be received, the first n are raw GPS, the second n are calculated results
if startTime is not None and dataReceived < numClientsData:
# we are in the first n received messages; forward the data to all other devices
dataReceived += 1
print "Have data from %s devices" % dataReceived
print "Data: %s" % str(self.data)
# forward message to all devices (except origin device)
for conn in self.server.connections.itervalues():
if conn != self:
conn.sendMessage(str(self.data))
elif startTime is not None and dataReceived == numClientsData:
# we are in the second n received messages; store the results
resultsReceived.append(self.data)
if len(resultsReceived) == numClientsData:
# we have finished collection; save end experiment timing, save, and reset the experiment
endTime = time.time()
print "%s Experiment complete" % endTime
saveResults()
reset()
def handleConnected(self):
global numClientsData
print self.address, "Connected Data"
numClientsData += 1
def handleClose(self):
global numClientsData
global startTime
print self.address, "closed Data"
numClientsData -= 1
# deal with disconnect during experiment
if startTime is not None:
print "---ERROR---\nClient disconnected (data) mid-experiment\n-----------"
startTime = None
serverControl = SimpleWebSocketServer('', 9000, ControlSocket)
serverData = SimpleWebSocketServer('', 9001, DataSocket)
# create two threads as follows
try:
thread.start_new_thread( serverControl.serveforever, () )
except:
print "Error: unable to start thread"
serverData.serveforever()
此外,我想打印正在生成的已解析 JSON 对象。
【问题讨论】:
【参考方案1】:您需要发回数据; print
只是写到你的终端。
使用self.sendMessage()
将字符串发送回客户端。请参阅自述文件的For the Programmers section。
以
def sendMessage(buffer)
:向客户端端点发送一些文本或二进制数据str()
发送缓冲区将发送基于文本的 WebSocket 帧,否则发送二进制帧
【讨论】:
以上是关于如何从简单的 Python 服务器打印到 html 页面?的主要内容,如果未能解决你的问题,请参考以下文章