• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python socket.write函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中socket.write函数的典型用法代码示例。如果您正苦于以下问题:Python write函数的具体用法?Python write怎么用?Python write使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了write函数的17个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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.")
开发者ID:bartosh,项目名称:pomni,代码行数:30,代码来源:client.py


示例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)
开发者ID:B-Rich,项目名称:exploitpack,代码行数:7,代码来源:DenialOfService80.py


示例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
开发者ID:ossobv,项目名称:earlyepp,代码行数:8,代码来源:eppsocket.py


示例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)
开发者ID:Bayonetta,项目名称:ZSChatSystem,代码行数:8,代码来源:server.py


示例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)
开发者ID:andreffs18,项目名称:django-instapush,代码行数:57,代码来源:apns.py


示例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")
开发者ID:dreamwave,项目名称:rad,代码行数:10,代码来源:socketserver.py


示例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
开发者ID:KirinDave,项目名称:powerset_thrift,代码行数:13,代码来源:TestSocket.py


示例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)
开发者ID:davidals,项目名称:django-push-notifications,代码行数:49,代码来源:apns.py


示例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()
开发者ID:justinlmeyer,项目名称:splunk-sdk-python,代码行数:12,代码来源:test_binding.py


示例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)
开发者ID:brianwhigham,项目名称:start-chromecast-CLI,代码行数:5,代码来源:__init__.py


示例11: send_get

 def send_get(self, socket, data):
     socket.write("GET /%s HTTP/1.0" % (self.path) )
     socket.write("\n\n")
开发者ID:aluarosi,项目名称:reactor.py,代码行数:3,代码来源:net.py


示例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
开发者ID:pseudonym,项目名称:plman,代码行数:95,代码来源:peer.py


示例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()
开发者ID:malmoore,项目名称:splunk-sdk-python,代码行数:19,代码来源:test_binding.py


示例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 = []
开发者ID:gans,项目名称:django-push-notifications,代码行数:29,代码来源:apns.py


示例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()
开发者ID:justinlmeyer,项目名称:splunk-sdk-python,代码行数:27,代码来源:test_binding.py


示例16: test_connect_with_preexisting_token_sans_user_and_pass

    def test_connect_with_preexisting_token_sans_user_and_pass(self):
        token = self.context.token
        opts = self.opts.kwargs.copy()
        del opts['username']
        del opts['password']
        opts["token"] = token

        newContext = binding.connect(**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()
开发者ID:justinlmeyer,项目名称:splunk-sdk-python,代码行数:22,代码来源:test_binding.py


示例17: RuntimeError

		None

		RETURNS:
		@message 	-- The message received from the currently connected
					   socket.
		'''

		# Read from the connected socket until the packet length is reached or
		# the maximum size is reached. When the entire message is recovered
		# string it together and return it. If at any point nothing is received
		# it is assumed that the connection was broken or the transmission
		# finished and what is in the buffer will be returned.
		chunks = []
		total_recieved = 0
		while total_recieved < 2048:
			chunk = self.sock.recv(min(2048 - total_recieved, 2048))
			if chunk == '':
				break
				raise RuntimeError('Connection Broken')
			chunks.append(chunk)
			total_recieved = total_recieved + len(chunk)
		return ''.join(chunks)	

if __name__ == '__main__':
	socket = TCPSocket('hello')
	socket.connect('104.131.44.2', 3000)
	socket.write('GET / HTTP/1.1\rHost: www.batphone.co\r\n\r\n')
	sleep(2)
	response = socket.read()
	print response
开发者ID:squidwardT,项目名称:batmanControlllerApplication,代码行数:30,代码来源:TCPSocket.py



注:本文中的socket.write函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python socket.socket类代码示例发布时间:2022-05-27
下一篇:
Python socket.timeout函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap