本文整理汇总了Python中socket.sendall函数的典型用法代码示例。如果您正苦于以下问题:Python sendall函数的具体用法?Python sendall怎么用?Python sendall使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了sendall函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: buildpath
def buildpath(socket, basedir, httpid):
"""Builds a directory path to a file from an HTTP request."""
request = socket.recv(4096)
print str(httpid) + " REQUEST"
print "Request recieved: " + request
reqlist = request.split()
print "Request in list form: " + str(reqlist)
print "Length of reqlist: " + str(len(reqlist))
if (len(reqlist) > 1):
if (reqlist[0] == "GET"):
endpath = reqlist[1]
abspath = basedir + str(endpath)
print "Full path constructed: " + str(abspath)
print (endpath)
else:
socket.sendall("HTTP/1.0 400 Bad Request\r\n")
socket.close
abspath = None
else:
socket.sendall("HTTP/1.0 400 Bad Request\r\n")
socket.close
abspath = None
return abspath
示例2: sokect_handler
def sokect_handler(self, socket, address):
if self.debug and logger.is_debug():
logger.get_logger().debug('%s: accept connection', address)
# send welcome
socket.sendall(Messager.data_for_welcome())
conn_inbox = Queue()
answer_thread = gevent.spawn(self.answer_fiber, socket, address, conn_inbox)
while self._running:
try:
message = Messager.receive_msg(socket)
if not message:
if self.debug and logger.is_debug():
logger.get_logger().debug('%s: connection has been closed by client.', address)
break;
if isinstance(message, Answer):
logger.get_logger().error('%s: unexpected message received: %s', address, message)
continue
elif isinstance(message, Query):
if self.debug and logger.is_debug():
logger.get_logger().debug('%s: message received: %s', address, message)
message.inbox = conn_inbox
self._query_queue.put(message)
except gevent.socket.error as ex:
logger.get_logger().error('%s: socket error: %s', address, repr(ex))
break
except:
logger.get_logger().error('%s: exception: %s', address, traceback.format_exc())
break
if self.debug and logger.is_debug():
logger.get_logger().debug('%s: close connection', address)
socket.close()
# stop answer thread
conn_inbox.put(StopIteration)
示例3: round
def round(self, player, move):
""" """
if (move[0] == constants.QUIT):
self.set_game_in_progress(False)
#TODO: make something to the end of the game
elif (move[0] == constants.CLICK):
# verifies if is the player's turn
if (player != self.get_player()):
pass
# verifies if is a empty square
elif (self.board.getSquare(move[1]) != 0):
pass
else:
try:
self.board.setSquare(move[1], self.player_indice + 1)
self.board.display()
msg = serialize.dumps((constants.DRAW, move[1], self.get_color()))
ignore, ready, ignore2 = select.select([], self.players, [], 0)
# checks if we have a winner
if self.end_game(move[1]):
self.set_game_in_progress(False)
print "end of the game"
# Draws the winner
msg = serialize.dumps((constants.WINNER, self.get_winner_coordinates(), self.get_color()))
ignore, ready, ignore2 = select.select([], self.players, [], 0)
for socket in ready:
socket.sendall(msg)
else:
for socket in ready:
socket.sendall(msg)
self.next_player()
finally:
self.server.close()
示例4: sendAllInt
def sendAllInt(socket, integerData):
try:
strLen = struct.pack('i', integerData)
socket.sendall(strLen)
except socket.error as msg:
return False
return True
示例5: servicerequest
def servicerequest(path, socket, httpid):
"""Services an HTTP request based on the provided file path"""
if (os.path.exists(path)):
print str(httpid) + " DELIVERED"
fd = open(path, "r")
file = fd.read()
okmsg = "HTTP/1.0 200 OK\r\n"
now = datetime.datetime.now()
datestr = now.strftime("%a %d %B %Y %H:%M:%S %z") + "\r\n"
print "Date and time: " + datestr
server = "Server: Var http-server 1.0\r\n"
connection = "Connection: close\r\n"
content_length = "Content length: " + str(sys.getsizeof(file)) + "\r\n"
content_type = "Content type: " + mimetypes.guess_type(path)[0] + "\r\n\r\n"
print content_type
print content_length
header = datestr + server + connection + content_length + content_type
socket.sendall(okmsg + header + file)
socket.close()
else:
print str(httpid) + " NOTFOUND"
socket.sendall("HTTP/1.0 404 Not Found\r\n")
socket.close()
print str(httpid) + " CLOSE"
return None
示例6: sendRequest
def sendRequest(self, socket):
print "Sending request to server\n"
HTTPcommand = sys.argv[3]
filePath = sys.argv[4]
if HTTPcommand in validHTTPRequestGet :
socket.send(HTTPcommand + " " + filePath + " "+ HTTPprotocol + CRLF )
size = 1024
data = ""
while True :
recvBuffer = socket.recv(size)
if recvBuffer == None or len(recvBuffer) == 0:
break;
data += recvBuffer
socket.close()
print 'Received:', data
elif HTTPcommand in validHTTPRequestPut:
if filePath == "/" :
filePath = "/index.html"
fileHandler = open("../WebContent" + filePath, "r")
print "Reading data from file to send payload to server\n"
payload = fileHandler.read()
fileHandler.close()
putRequest = HTTPcommand + " " + filePath + " " + HTTPprotocol + CRLF + "Host: my simple client" + CRLF + CRLF + "data=" + payload
socket.sendall(putRequest)
print "Sent data to server\n "
socket.close()
else:
print "Bad request"
socket.close()
示例7: mangodb
def mangodb(socket, address):
socket.sendall('HELLO\r\n')
client = socket.makefile()
output = open(os.devnull, 'w')
lock = threading.Lock()
wait = threading.Condition(lock)
while 1:
line = client.readline()
if not line:
break
cmd_bits = line.split(' ', 1)
cmd = cmd_bits[0]
if cmd == 'BYE':
break
if cmd == 'WAIT':
wait.wait()
continue
if len(cmd_bits) > 1:
lock.acquire(True)
output.write(cmd_bits[1])
if MANGODB_DURABLE:
output.flush()
os.fsync(output.fileno())
data = '42' if MANGODB_EVENTUAL else \
os.urandom(1024).encode('string-escape')
lock.release()
client.write('OK' + data + '\r\n')
client.flush()
示例8: checkConnection
def checkConnection(socket) :
global username
socket.sendall(SECURITY_PASS + '\n' + username)
reply = socket.recv(1024)
log('Received ' + reply)
con = reply == OK_MESSAGE
return con
示例9: send_message
def send_message(self, socket, data):
try:
socket.sendall(data)
#except socket.error, e:
except Exception, (error, message):
print 'Error sending data. Exiting...'
sys.exit()
示例10: _writeWrapper
def _writeWrapper(self, socket, data):
try:
socket.sendall(bytes(data + "\r\n", 'utf-8'))
except OSError:
self.shutdown()
raise
示例11: send
def send(request, socket):
try:
socket.sendall(request.encode('utf-8'))
socket.sendall(b'\n')
except Exception as e:
service_down(message=str(e), exception=e)
raise e
示例12: _socketRequest
def _socketRequest(self, scheme, host, port, payload):
socket = self._getSocketForScheme(scheme)
socket.connect((host, port))
socket.sendall(payload)
data = socket.recv(1024)
socket.close()
return data
示例13: POST
def POST(self, url, args=None):
host, port, path = self.parse_url(url)
socket = self.connect(host, port)
if args == None:
arguments = ""
else:
arguments = urllib.urlencode(args)
request = "POST %s HTTP/1.1\n" % path
request += "Host: %s\n" % host
request += "Content-Type: application/x-www-form-urlencoded\n"
request += "Content-Length: %s\n" % len(arguments)
request += "Connection: close" + self.TERMINATE
request += arguments + self.TERMINATE
socket.sendall(request)
response = self.recvall(socket)
socket.close()
code = self.get_code(response)
#body = self.get_post_body(response, args)
body = self.get_body(response)
print response
return HTTPRequest(code, body)
示例14: client
def client(self,socket,addr):
infoName="SocketWriter-%s"%(unicode(addr),)
self.setName("[%s]%s-Writer %s"%(AVNLog.getThreadId(),self.getName(),unicode(addr)))
self.setInfo(infoName,"sending data",AVNWorker.Status.RUNNING)
if self.getBoolParam('read',False):
clientHandler=threading.Thread(target=self.clientRead,args=(socket, addr))
clientHandler.daemon=True
clientHandler.start()
filterstr=self.getStringParam('filter')
filter=None
if filterstr != "":
filter=filterstr.split(',')
try:
seq=0
socket.sendall("avnav_server %s\r\n"%(VERSION))
while True:
hasSend=False
seq,data=self.feeder.fetchFromHistory(seq,10)
if len(data)>0:
for line in data:
if NMEAParser.checkFilter(line, filter):
socket.sendall(line)
hasSend=True
else:
time.sleep(0.1)
pass
if not hasSend:
#just throw an exception if the reader potentially closed the socket
socket.getpeername()
except Exception as e:
AVNLog.info("exception in client connection %s",traceback.format_exc())
AVNLog.info("client disconnected")
socket.close()
self.removeHandler(addr)
self.deleteInfo(infoName)
示例15: push
def push(self, metrics, socket=None, logging_prefix=''):
"""
:param metrics: An iterable of string, each repreasenting a metric data
"""
"""A list of strings representing metrics"""
docs = list()
for metric in metrics:
if metric == 'version' and socket is not None:
socket.sendall( (VERSION + '\n').encode() )
line = self.parser.parse(metric, logging_prefix=logging_prefix)
if line is None:
continue
self.lock.acquire()
self.buffer.append({'_index': self.index,
'_type': line[0],
'_source': line[1]})
current_time = time.time()
if len(self.buffer) > self.buffer_size or (current_time - self.last_flush) > 60:
self.flush()
self.last_flush = current_time
self.lock.release()