本文整理汇总了Python中socket.sendall函数的典型用法代码示例。如果您正苦于以下问题:Python sendall函数的具体用法?Python sendall怎么用?Python sendall使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了sendall函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:laget,项目名称:Project-4,代码行数:26,代码来源:3600http.py
示例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)
开发者ID:liaohuqiu,项目名称:cube-rpc-python,代码行数:35,代码来源:engine.py
示例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()
开发者ID:nancibonfim,项目名称:gomoku,代码行数:34,代码来源:gomoku.py
示例4: sendAllInt
def sendAllInt(socket, integerData):
try:
strLen = struct.pack('i', integerData)
socket.sendall(strLen)
except socket.error as msg:
return False
return True
开发者ID:kudocc,项目名称:python-srFile,代码行数:7,代码来源:client.py
示例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
开发者ID:laget,项目名称:Project-4,代码行数:34,代码来源:3600http.py
示例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()
开发者ID:mrunaln,项目名称:HTTPclientServer,代码行数:31,代码来源:client.py
示例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()
开发者ID:eklitzke,项目名称:mangodb,代码行数:28,代码来源:server.py
示例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
开发者ID:emurphy-9,项目名称:DistributedFileSystem,代码行数:7,代码来源:client.py
示例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()
开发者ID:littledanby,项目名称:computer-network,代码行数:7,代码来源:Server.py
示例10: _writeWrapper
def _writeWrapper(self, socket, data):
try:
socket.sendall(bytes(data + "\r\n", 'utf-8'))
except OSError:
self.shutdown()
raise
开发者ID:yakcyll,项目名称:wrtm-tester,代码行数:7,代码来源:N2xInterface.py
示例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
开发者ID:HackerDom,项目名称:ructf-2016,代码行数:7,代码来源:cleaner.exploit2.py
示例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
开发者ID:buglloc,项目名称:pocs,代码行数:7,代码来源:file_uploader.py
示例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)
开发者ID:bsmolley,项目名称:CMPUT404-assignment-web-client,代码行数:26,代码来源:httpclient.py
示例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)
开发者ID:jhedtmann,项目名称:avnav,代码行数:35,代码来源:socketwriter.py
示例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()
开发者ID:Gueust,项目名称:elasticsearch-metrics-tools,代码行数:26,代码来源:elasticsearch_injector.py
示例16: serviceClientsOut
def serviceClientsOut(self):
while 1:
self.commandsEvent.wait()
try:
###dispatch individual commands
self.indivCommandsLock.acquire()
while self.indivCommands:
self.socketsLock.acquire()
socket = self.sockets[self.indivCommands[0][0]]
socket.sendall(self.indivCommands[0][1]+self.term)
self.socketsLock.release()
self.indivCommands.pop(0)
self.indivCommandsLock.release()
### dispatch commands to each socket connected
self.commandLock.acquire()
while self.commands:
self.socketsLock.acquire()
for socket in self.sockets.values():
socket.sendall(self.commands[0]+self.term)
self.socketsLock.release()
if BotWars.DEBUG:
print "server send: "+self.commands[0]
pass
self.commands.pop(0)
self.commandLock.release()
self.commandsEvent.clear()
###capture disconnects and remove those sockets from the list
### release any locked locks
### kill service thread if no more sockets remain
except error , se:
self.handleError(socket)
开发者ID:lovi9573,项目名称:BotWars,代码行数:33,代码来源:tcp.py
示例17: parse_sent_data
def parse_sent_data(data, socket):
if data[0:9] == 'userName/':
# Username the client chose for himself
user_connected = data[9:len(data)]
dup = False
# Check if it is a duplicate
for key, val in user_dic:
if user_dic[key, val] == user_connected:
dup = True;
break
if (dup):
socket.sendall(str("DUPNAME"))
return None
# Add to the client dicionary the userName as value and the sockname as key
update_user_list(socket.getpeername(), user_connected)
return None
elif data[0:10] == '--userList':
# User requested the user list of the site
user_names_to_return = [];
for (sock_String, port_value) in user_dic:
user_names_to_return.append(user_dic[(sock_String, port_value)])
socket.sendall(str(user_names_to_return))
return None
elif data == "CLOSEDCONNECTION":
# Client has signaled it is disconnecting
remove_client(socket)
return None
else:
return data
开发者ID:asafliv,项目名称:SimplePythonChat,代码行数:30,代码来源:snakeChatServer.py
示例18: send
def send(socket, message):
# Send the length of the message.
# Should work as long as we send messages shorter than ~10 googol chars
length = str(len(message)).encode('utf-8')
socket.sendall(length)
# Send the message
socket.sendall(message.encode('utf-8'))
开发者ID:nwlongnecker,项目名称:CS557RefMon,代码行数:7,代码来源:network_protocol.py
示例19: sendFile
def sendFile(fname, socket):
blockSize = 32000
msg = ''
try:
source = open(fname, 'rb')
sizeBytes = os.path.getsize(fname)
utils.log('Sending file ' + fname + ' of ' + str(sizeBytes) + ' bytes')
bytesOut = 0
start = utils.getUTCTime()
prev = 0
for data in utils.chunked(source, blockSize):
utils.log('sending data ' + str(len(data)))
socket.sendall(data)
bytesOut += len(data)
if (bytesOut - sizeBytes) > 1024:
utils.log('WARNING - truncating send because send file appears to be growing.')
break;
diff = utils.getSecondsBetweenTwoDates(start, utils.getUTCTime())
diff = (int(diff/30))*30
if diff > prev:
prev = diff
utils.log('So far sent ' + str(bytesOut) + ' read')
utils.log('Completed send of ' + str(bytesOut) + ' bytes')
socket.settimeout(20)
c = socket.recv(4096)
utils.log('Received ' + repr(c))
return msg
#except(socket.error):
#utils.log("timeout in sendFile - possibly no received confirmation data")
except Exception, errorcode:
if errorcode[0] != "timed out":
utils.logTrace('Exception ' + repr(errorcode))
开发者ID:pgrossma,项目名称:petri,代码行数:33,代码来源:utils.py
示例20: get_pending
def get_pending(self,socket) :
header = self.get_header(14,701)
socket.sendall(header)
print "packet sent"
header1 = socket.recv(14) #recieve header packet
size = header1[2:4] #size of whole packet= 14
size = struct.unpack('h',size)
msg = header1[4:6] #messagecode
msg = struct.unpack('h',msg)
print "receiving Pending Orders Start"
print str(msg[0]) +" " + str(size[0])
if msg[0] != 702 :
print "Error in Pending Orders Start"
return -1
while True :
header2 = socket.recv(14)
size2 = header2[2:4] #size of whole packet= 14 +229
size2 = struct.unpack('h',size2)
msg2 = header2[4:6] #messagecode
msg2 = struct.unpack('h',msg2)
if msg2[0] == 704 :
print msg2[0]
print "Pending Orders Process End"
return 0
elif msg2[0] == 703:
print "\n"
#print " receiving Pending Orders Process"
else :
print msg2[0]
print "Pending Orders Process Error"
return 0
packet = socket.recv(size2[0]-14) #recieve Order packet
print "receiving Pending Orders Response"
print str(msg2[0]) +" " + str(size2[0])
print packet
exch=packet[0:10] #0=14-14, 10=24-14
exch = struct.unpack('10s', exch)[0]
initqty=packet[130-14:134-14]
initqty=struct.unpack('I', initqty)
lprice=packet[142-14:150-14]
lprice= struct.unpack('d', lprice)
ordertype=packet[190-14:202-14]
ordertype= struct.unpack('12s', ordertype)[0]
print "\nSample::" + exch + " " + str(initqty[0])+" "+str(lprice[0]) +" " + ordertype
print "=========================================================="
开发者ID:ashgen,项目名称:NSEDataAnalytics,代码行数:59,代码来源:Sample_Response_Packets.py
注:本文中的socket.sendall函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论