本文整理汇总了Python中socket.write函数的典型用法代码示例。如果您正苦于以下问题:Python write函数的具体用法?Python write怎么用?Python write使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了write函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: put_client_media_files
def put_client_media_files(self, reupload_all=False):
self.ui.status_bar_message("Sending media files to server...")
# Size of tar archive.
if reupload_all:
filenames = self.database.all_media_filenames()
else:
filenames = self.database.media_filenames_to_sync_for(\
self.server_info["machine_id"])
size = tar_file_size(self.database.mediadir(), filenames)
if size == 0:
return
self.con.putrequest("PUT", "/client_media_files?session_token=%s" \
% (self.server_info["session_token"], ))
self.con.endheaders()
socket = self.con.sock.makefile("wb", bufsize=BUFFER_SIZE)
socket.write(str(size) + "\n")
# Bundle the media files in a single tar stream, and send it over a
# buffered socket in order to save memory. Note that this is a short
# cut for efficiency reasons and bypasses the routines in Partner, and
# in fact even httplib.HTTPConnection.send.
saved_path = os.getcwdu()
os.chdir(self.database.mediadir())
tar_pipe = tarfile.open(mode="w|", # Open in streaming mode.
format=tarfile.PAX_FORMAT, fileobj=socket)
for filename in filenames:
tar_pipe.add(filename)
tar_pipe.close()
os.chdir(saved_path)
if self.con.getresponse().read() != "OK":
raise Exception("Error sending media files to server.")
示例2: cycle_identity
def cycle_identity():
socket = make_socket("localhost", "9050")
socket.write("AUTHENTICATE \"\"\n")
while True:
socket.write("signal NEWNYM\n\x00")
print "[" + str(socket) + ": cycle_identity -> signal NEWNYM\n"
time.sleep(300000/1000000.0)
示例3: main
def main():
socket = tcp_connect('testdrs.my-domain-registry.nl')
socket.write("""<?xml version="1.0" encoding="UTF-8" standalone="no"?><epp xmlns="urn:ietf:params:xml:ns:epp-1.0"><hello/></epp>""")
data = socket.read()
print data
data = socket.read()
socket.close()
print data
示例4: broadcast_data
def broadcast_data (sock,message):
for socket in conn_list:
if socket != server_socket and socket != sock :
try :
socket.write(message)
except :
socket.close()
conn_list.remove(socket)
示例5: _apns_send
def _apns_send(token, alert, badge=None, sound="default", category=None, content_available=True,
action_loc_key=None, loc_key=None, loc_args=[], extra={}, identifier=0,
expiration=None, priority=10, socket=None, **kwargs):
data = {}
aps_data = {}
custom_params = alert
alert = custom_params.pop('message')
if action_loc_key or loc_key or loc_args:
alert = {"body": alert} if alert else {}
if action_loc_key:
alert["action-loc-key"] = action_loc_key
if loc_key:
alert["loc-key"] = loc_key
if loc_args:
alert["loc-args"] = loc_args
if alert is not None:
aps_data["alert"] = alert
if badge is not None:
aps_data["badge"] = badge
if sound is not None:
aps_data["sound"] = sound
if category is not None:
aps_data["category"] = category
if content_available:
aps_data["content-available"] = 1
if custom_params.keys():
aps_data['custom_params'] = {'data': custom_params}
data["aps"] = aps_data
data.update(extra)
# convert to json, avoiding unnecessary whitespace with separators (keys sorted for tests)
json_data = json.dumps(data, separators=(",", ":"), sort_keys=True).encode("utf-8")
max_size = SETTINGS["MAX_SIZE"]
if len(json_data) > max_size:
raise APNSDataOverflow("Notification body cannot exceed %i bytes" % (max_size))
# if expiration isn't specified use 1 month from now
expiration_time = expiration if expiration is not None else int(time.time()) + 2592000
frame = _apns_pack_frame(token, json_data, identifier, expiration_time, priority)
if socket:
socket.write(frame)
else:
with closing(_apns_create_socket_to_push(**kwargs)) as socket:
socket.write(frame)
_apns_check_errors(socket)
示例6: send
def send(self, id, str):
socket = self.client_table[id]
socket.write("start")
totalsent = 0
while totalsent < str.__len__():
sent = socket.write(str[totalsent:])
if sent == 0:
raise RuntimeError, "socket connection broken"
totalsent = totalsent + sent
socket.write("end")
示例7: testWriteTimeout
def testWriteTimeout(self):
starttime = time.time()
try:
socket = TSocket.TSocket('localhost', self.port)
socket.setTimeout(10)
socket.open()
lsock = self.listen_sock.accept()
while True:
socket.write("hi" * 100)
except:
assert time.time() - starttime < 5.0
示例8: _apns_send
def _apns_send(token, alert, badge=0, sound=None, content_available=False, action_loc_key=None, loc_key=None,
loc_args=[], extra={}, identifier=0, expiration=None, priority=10, socket=None, logger=None):
data = {}
aps_data = {}
if action_loc_key or loc_key or loc_args:
alert = {"body": alert} if alert else {}
if action_loc_key:
alert["action-loc-key"] = action_loc_key
if loc_key:
alert["loc-key"] = loc_key
if loc_args:
alert["loc-args"] = loc_args
if alert is not None:
aps_data["alert"] = alert
if badge:
aps_data["badge"] = badge
if sound is not None:
aps_data["sound"] = sound
if content_available:
aps_data["content-available"] = 1
data["aps"] = aps_data
data.update(extra)
# convert to json, avoiding unnecessary whitespace with separators
json_data = json.dumps(data, separators=(",", ":"))
if(logger is not None):
logger.debug(json_data)
if len(json_data) > APNS_MAX_NOTIFICATION_SIZE:
raise APNSDataOverflow("Notification body cannot exceed %i bytes" % (APNS_MAX_NOTIFICATION_SIZE))
# if expiration isn't specified use 1 month from now
expiration_time = expiration if expiration is not None else int(time.time()) + 2592000
frame = _apns_pack_frame(token, json_data, identifier, expiration_time, priority)
if socket:
socket.write(frame)
else:
with closing(_apns_create_socket()) as socket:
socket.write(frame)
_apns_check_errors(socket)
示例9: test_unicode_socket
def test_unicode_socket(self):
socket = self.context.connect()
socket.write(u"POST %s HTTP/1.1\r\n" %\
self.context._abspath("some/path/to/post/to"))
socket.write(u"Host: %s:%s\r\n" %\
(self.context.host, self.context.port))
socket.write(u"Accept-Encoding: identity\r\n")
socket.write(u"Authorization: %s\r\n" %\
self.context.token)
socket.write(u"X-Splunk-Input-Mode: Streaming\r\n")
socket.write("\r\n")
socket.close()
示例10: write_to_socket
def write_to_socket(socket, namespace, data):
lnData = getLenOf(data)
msg = pack(">BBBB%dsBB%dsBB%dsBBB%ds%ds" % (len("sender-0"),len("receiver-0"),len(namespace),len(lnData),len(data)),getType(1,TYPE_ENUM),0,getType(2,TYPE_STRING),len("sender-0"),"sender-0",getType(3,TYPE_STRING),len("receiver-0"),"receiver-0",getType(4,TYPE_STRING),len(namespace),namespace,getType(5,TYPE_ENUM),0,getType(6,TYPE_BYTES),lnData,data)
msg = pack(">I%ds" % (len(msg)),len(msg),msg)
socket.write(msg)
示例11: send_get
def send_get(self, socket, data):
socket.write("GET /%s HTTP/1.0" % (self.path) )
socket.write("\n\n")
示例12: on_data
def on_data(self, socket, data):
pos = data.find('\n')
if pos < 0: # need to wait for new line
return 0
elif pos == 0:
return 1 # just a keep-alive
args = data[0:pos].split(' ')
if self.DEBUG: print 'inT:', ' '.join(args)
# client->server commands:
# CGET hash -- get value with specified hash
# CPUT data -- put data into hash table (base64-encoded)
# CSHOW -- request a listing of all nodes
# server->client commands:
# CERROR msg -- there was some kind of error
# CDATA data -- data that was stored (base64-encoded)
# COK hash -- insert succeeded
# CPEER hash ip:port -- peer in system
if args[0] == 'CGET':
hash = args[1]
t = Trans(Trans.GET, self, socket)
t.add()
self.find(hash, t.id)
elif args[0] == 'CPUT':
to_add = base64.b64decode(args[1])
hash = make_file_id(to_add)
t = Trans(Trans.PUT, self, socket, to_add)
t.add()
self.find(hash, t.id)
elif args[0] == 'CSHOW':
t = Trans(Trans.SHOW, self, socket)
t.add()
if self.finger[0] != self.myname:
# we can have trouble here if a node just joined and our successor
# has not been updated to reflect that
self.dgram_socket.send(self.finger[0], ['SHOW', self.myname, t.id])
socket.write(['CPEER', make_id(self.myname), self.myname])
# get/put operations done over TCP because data could be larger than 1 packet
# GET hash transid -- request for data
# DATA data transid -- hash and its data (sent in response to GET)
# ERROR msg transid -- there was an error
# PUT data transid -- data to insert (hash calculated at inserting node)
# OK hash transid -- insert succeeded
elif args[0] == 'GET':
(hash, transid) = args[1:]
if hash in self.items:
socket.write(['DATA', base64.b64encode(self.items[hash]), transid])
else:
socket.write(['ERROR', 'data.not.found', transid])
socket.close_when_done()
elif args[0] == 'DATA':
(data, transid) = args[1:]
t = self.trans[transid]
t.client.write(['CDATA', data])
t.client.close_when_done()
t.remove()
elif args[0] == 'ERROR':
(msg, transid) = args[1:]
t = self.trans[transid]
t.client.write(['CERROR', msg])
t.client.close_when_done()
t.remove()
elif args[0] == 'PUT':
(data, transid) = args[1:]
data = base64.b64decode(data)
hash = make_file_id(data)
print 'adding %s' % hash
self.items[hash] = data
socket.write(['OK', hash, transid])
socket.close_when_done()
elif args[0] == 'OK':
(hash, transid) = args[1:]
t = self.trans[transid]
t.client.write(['COK', hash])
t.client.close_when_done()
t.remove()
# value transfers are done over TCP as well
# RETR low high -- ask for data in range (low, high]
# XFER hash data -- response to RETR (transferring data to new node)
elif args[0] == 'RETR':
(low, high) = args[1:]
for i in self.items.iterkeys():
if id_distance(low, i) < id_distance(low, high):
print 'transferring %s to peer' % i
socket.write(['XFER', i, base64.b64encode(self.items[i])])
socket.close_when_done()
elif args[0] == 'XFER':
(hash, data) = args[1:]
# add to database
self.items[hash] = base64.b64decode(data)
else:
print 'unknown message:', ' '.join(args)
return pos + 1
示例13: test_preexisting_token
def test_preexisting_token(self):
token = self.context.token
opts = self.opts.kwargs.copy()
opts["token"] = token
opts["username"] = "boris the mad baboon"
opts["password"] = "nothing real"
newContext = binding.Context(**opts)
response = newContext.get("/services")
self.assertEqual(response.status, 200)
socket = newContext.connect()
socket.write("POST %s HTTP/1.1\r\n" % self.context._abspath("some/path/to/post/to"))
socket.write("Host: %s:%s\r\n" % (self.context.host, self.context.port))
socket.write("Accept-Encoding: identity\r\n")
socket.write("Authorization: %s\r\n" % self.context.token)
socket.write("X-Splunk-Input-Mode: Streaming\r\n")
socket.write("\r\n")
socket.close()
示例14: int
# if expiration isn't specified use 1 month from now
expiration_time = expiration if expiration is not None else int(time.time()) + 2592000
frame = _apns_pack_frame(token, json_data, identifier, expiration_time, priority)
if socket:
try:
socket.write(frame)
except Socket.error, e:
if e[0] == errno.EPIPE:
raise APNSServerError(20, identifier)
raise APNSServerError(255, identifier)
else:
with closing(_apns_create_socket_to_push()) as socket:
socket.write(frame)
_apns_check_errors(socket)
def _apns_read_and_unpack(socket, data_format):
length = struct.calcsize(data_format)
data = socket.recv(length)
if data:
return struct.unpack_from(data_format, data, 0)
else:
return None
def _apns_receive_feedback(socket):
expired_token_list = []
示例15: test_preexisting_token_sans_splunk
def test_preexisting_token_sans_splunk(self):
token = self.context.token
if token.startswith('Splunk '):
token = token.split(' ', 1)[1]
self.assertFalse(token.startswith('Splunk '))
else:
self.fail('Token did not start with "Splunk ".')
opts = self.opts.kwargs.copy()
opts["token"] = token
opts["username"] = "boris the mad baboon"
opts["password"] = "nothing real"
newContext = binding.Context(**opts)
response = newContext.get("/services")
self.assertEqual(response.status, 200)
socket = newContext.connect()
socket.write("POST %s HTTP/1.1\r\n" %\
self.context._abspath("some/path/to/post/to"))
socket.write("Host: %s:%s\r\n" %\
(self.context.host, self.context.port))
socket.write("Accept-Encoding: identity\r\n")
socket.write("Authorization: %s\r\n" %\
self.context.token)
socket.write("X-Splunk-Input-Mode: Streaming\r\n")
socket.write("\r\n")
socket.close()