当前位置: 首页>>代码示例>>Python>>正文


Python socket.recv函数代码示例

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


在下文中一共展示了recv函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: monitorIncoming

 def monitorIncoming(self):
     while 1:
         r,w,e = select.select([self.s], [], [])
         
         ### check if anything has been sent
         if r:
             for socket in r:
                 data = socket.recv(9)
                 size = int(data[:9])
                 data = data[9:]
                 bytesrecvd = len(data)
                 
                 while bytesrecvd < size:
                     #print "hello"
                     #print "size:",size,"bytesrecvd:",bytesrecvd
                     buffsize = self.size
                     if ((size-bytesrecvd) < self.size):
                         buffsize = size-bytesrecvd
                         d = socket.recv(buffsize)
                         #print "data:",d,"buffsize:",buffsize
                         data += d
                     else:
                         data += socket.recv(buffsize)
                     bytesrecvd = len(data)
                 self.commandLock.acquire()
                 self.queueCommand(data)
                 #print "Client.monitorIncoming command list:",self.commands
                 if BotWars.VERBOSE:
                     #print "client recieve: ", pickle.loads(cmd[:-1]),"\n"
                     pass
                 self.ismore.set()
                 self.commandLock.release()
开发者ID:lovi9573,项目名称:BotWars,代码行数:32,代码来源:tcp2.py

示例2: recv_data

def recv_data(socket):
    """Receive data via the connection "socket" """
    
    # FIXME: use list to drastically improve performance
    # do something like
    # data = []
    # data.append(recv())
    # return string.join(data, '')
    
    # get the data size
    data_size = string.atoi(socket.recv(Protocol.DATA_LENGTH), 16)
    
    # get the data
    data = ""
    tmp_data = socket.recv(data_size)
    data_received_so_far = len(tmp_data)
    data += tmp_data
    
    while data_received_so_far < data_size:
        tmp_data = socket.recv(data_size - data_received_so_far)
        data_received_so_far += len(tmp_data)
        data += tmp_data

    #    return lzo.decompress(data)
    return data
开发者ID:misterdjules,项目名称:DMS,代码行数:25,代码来源:ProtocolUtils.py

示例3: result

def result(socket, ab_and_s, mapping):
  a, b, s = ab_and_s
  message = socket.recv(1024)
  tokens  = message.split()

  #wrong answer
  if(len(tokens)==6):
    acount = mapping[a]
    bcount = mapping[b]

    if(a == s):
      mapping[b] = acount+1
    else: 
      mapping[a] = bcount+1

    socket.close()

    socket = start_game()
    message = socket.recv(1024)
    return [message, socket]

  #reached the end
  if(len(tokens)==2):
    print("You won!\n")
    return [None, None]

  # correct answer
  return [message, socket]
开发者ID:goose3gg,项目名称:Puzzles,代码行数:28,代码来源:player.py

示例4: recvall

def recvall(socket):
    data = ''
    more = socket.recv(MAX) 
    while more:
        data += more
        more = socket.recv(MAX)
    return data
开发者ID:akaptur,项目名称:echo,代码行数:7,代码来源:tcp_echo.py

示例5: recv_message

    def recv_message(socket):
        logging.debug("network::Network::recv_message: Function call")

        wait_status = Network.wait_for_data(socket, Network.TIMEOUT_SECONDS)
        if wait_status != Network.WaitStatus.NEW_DATA:
            logging.error("network::Network::recv_message: Timeout")
            raise Network.TimeoutException

        logging.debug("network::Network::recv_message: Receiving first part")
        received = socket.recv(1)
        if len(received) != 1:
            logging.error("network::Network::recv_message: Received " + str(len(received)) + " bytes, expected 1")
            raise IOError("Received " + str(len(received)) + " bytes, expected 1")

        message_length = struct.unpack('B', received)[0]

        logging.debug("network::Network::recv_message: Receiving message")
        message = ''
        while len(message) < message_length:
            left_to_receive = message_length - len(message)

            wait_status = Network.wait_for_data(socket, Network.TIMEOUT_SECONDS)
            if wait_status != Network.WaitStatus.NEW_DATA:
                logging.debug("network::Network::recv_message: Timeout")
                raise Network.TimeoutException

            message += socket.recv(left_to_receive)

        logging.debug("network::Network::recv_message: Received")
        return message
开发者ID:chyla,项目名称:pat-lms,代码行数:30,代码来源:network.py

示例6: _call

    def _call(socket, app, name, arguments):
        """
        Proxify a call to the remote end point and parse the result

        Keyword arguments:
        name      -- name of the remote method
        arguments -- list of arguments for the method
        """
        # send the request
        request = json.dumps([app, name] + list(arguments))
        message = struct.pack('>I', len(request)) + request

        while len(message) > 0:
            message = message[socket.send(message):]

        # wait for the answer
        length = socket.recv(4)
        assert len(length) == 4, IOError("Connection error while receiving")
        length = struct.unpack('>I', length)[0]
        # receive as many bytes from the tcp socket
        result = ''
        while len(result) < length:
            recv = socket.recv(length - len(result))
            if len(recv) == 0:
                break
            result += recv
        # always check the message length
        assert len(result) == length, IOError("Wrong message length")
        # decode the answer
        response = json.loads(result)
        if not response['success']:
            raise RuntimeError("Remote error, %s" % response['response'])
        return None if 'response' not in response else response['response']
开发者ID:biddyweb,项目名称:gadget-client,代码行数:33,代码来源:proto.py

示例7: tcpReceive

def tcpReceive(socket, ip):
	global inNodes, lock
	try:
		if ip not in inNodes:
			inNodes.update({ip:[0,'unkown']})
		print 'Got connection from: %s, %s' % (ip, inNodes[ip][1])
		
		#parse data
		msg = ''
		data = socket.recv(1024 * 10)
		i = 0
		while data:
			msg += data
			data = socket.recv(1024)		
			i += 1
	
		print 'msg:', msg
		
		while lock:
			time.sleep(.01)
		lock = True
		
		try:
			inNodes[ip][0] = int(msg)
		except:
			pass
		finally:
			lock = False
	
		#socket.send('I got your message %s\n' % inNodes[ip][1])
	except Exception, e:
		print 'Receive failed...', e
开发者ID:miedwards,项目名称:boids,代码行数:32,代码来源:peter_code.py

示例8: pull_file

def pull_file(path, socket, buf_size=1024):
    """
    Given a path to a writable file and a socket, receive YASA transmitted 
    data over the socket and write it to a new file at `path`. Returns the
    hash of the file _according to the sender_.
    """
    logging.debug('GOT FILE  <- %s' % path)
    fd = open(path, 'wb')

    buf = ''
    while '\n' not in buf:
        buf += socket.recv(10).decode('utf-8')

    flen, buf = buf.split('\n', 1)
    flen = int(flen.strip())
    totes = len(buf)
    fd.write(buf)

    while totes < flen:
        buf = socket.recv(min(1024, flen-totes))
        totes += len(buf)
        fd.write(buf)

    totes = 0
    buf = ''
    while len(buf) < 16:
        buf += socket.recv(16-len(buf))

    fd.close()

    return buf
开发者ID:RyanJenkins,项目名称:YASA,代码行数:31,代码来源:utils.py

示例9: get_message

def get_message(socket, digits=4,status=False):
  """
  <Purpose>
    Retrieves a full messsage from the socket. Each message is prepended with 'digits' number of digits,
    which indicate the length of the proceding message.

  <Arguments>
    socket: A TCP socket
    digits: Defaults to 4, the number of prepended digits to check for.
    status: If true, it will print the bytes remaining to be downloaded.

  <Returns>
    The message.
  """

  # Get the length of the user message
  length = int(socket.recv(digits))
  
  # Get the message
  message = ""
  remaining = length
  while remaining > 0:
    if status: print "Bytes Remaining:",remaining
    part = socket.recv(remaining)
    additional = len(part)
    if additional == 0:
      raise Exception, "Connection Terminated!"
    else:
      remaining -= additional
      message += part
  
  return message
开发者ID:Ashmita89,项目名称:integrationtests,代码行数:32,代码来源:testingserver.py

示例10: serviceClientsIn

 def serviceClientsIn(self):
     data = ""
     while 1:
         ### check the readable status of each socket(has client sent anything)
         #print "server in sleep"
         #time.sleep(.1) #needed to avoid a hang btween server/client?
         
         while not self.sockets:
             pass
         #self.socketsLock.acquire()
         r,w,e = select.select(self.sockets.values(),[],[],.1)
         #self.socketsLock.release()
         #print "serviceClientsIn loop"
         if r:  #Data has been sent on the following sockets
             try:
                 self.socketsLock.acquire()
                 for socket in r:
                     data = socket.recv(self.size)
                     while data[-4:] != self.term:
                         if BotWars.VERBOSE:
                             print "server retrieving rest of unsent data"
                         data +=  socket.recv(self.size)
                     self.indivRequestsLock.acquire()
                     self.indivRequests.append((socket.fileno(),data[:-4]))
                     if BotWars.VERBOSE:
                         #print "Server Recieve: " +pickle.loads(data[:-1])[0]
                         pass
                     self.indivRequestsLock.release()
                     self.ismore.set()
                 self.socketsLock.release()
             except error, ae:
                 self.handleError(socket)
开发者ID:lovi9573,项目名称:BotWars,代码行数:32,代码来源:tcp.py

示例11: receive_files

def receive_files(socket):
    fileno = socket.recv(512) #receive the number of files to be sent
    print ("Number of files expected: "), fileno
    
    for x in range(0, int(fileno)):
        print("Receiving file "), x+1 , ("of "), fileno
        dat = socket.recv(1024)
        dat = dat.replace("%%%%", getpass.getuser())

        if dat != "null":
            path.append(dat) #get path of incomming file
            time.sleep(0.5)
            size = socket.recv(1024) #get size of file
            print("Receiving "),size,("bytes")
            time.sleep(0.5)
            buff = socket.recv(int(size)) #get actual file content
            print("Writing file to "), path[x-1] 
            f = open(path[x-1], 'wb') #open new file
            f.write(buff) #write content to file.
            print ("File written")
            socket.send('1')
            time.sleep(0.5)
        else:
            print("File number '"),x+1,(" is being ignored by sender.")
            time.sleep(0.5)
                        
    return      
开发者ID:Samathy,项目名称:dotsync,代码行数:27,代码来源:receive.py

示例12: recv_data_from_nodes

def recv_data_from_nodes(dist_map, count):
	node_sockets = dist_map.keys()

	total_to_be_read = 0
	for x in dist_map:
		index_lists = dist_map[x]
		total_to_be_read += len(index_lists)
	store_total_to_be_read = total_to_be_read;
	iterations = 0
	while total_to_be_read:
		readable, writable, exceptional = select.select(node_sockets, [], [], max(30, count/2))
		if len(readable) == 0 and len(writable) == 0 and len(exceptional) == 0:
			iterations += 1
			if store_total_to_be_read > total_to_be_read or iterations >= 2:
				print "timed out"
				return []
			else:
				continue
		for socket in readable:
			recv_size = socket.recv(10)
			if len(recv_size) == 0:
				print "node closed connection", socket
				node_sockets.remove(socket)
				continue;
			try:
				recv_size = int(recv_size)
			except:
				print "Recv size is not int"
				return []
			recv_start_index = socket.recv(10)
			if len(recv_start_index) == 0:
				print "node closed connection", socket
				node_sockets.remove(socket)
				continue;
			try:
				recv_start_index = int(recv_start_index)
			except:
				print "Recv start index is not int"
				return []
			print "Receiving size", recv_size
			print "Receiving start index", recv_start_index

			recv_data = socket.recv(recv_size)
			if len(recv_data) == 0:
				print "node closed connection", socket
				node_sockets.remove(socket)
				continue;

			local_map = pickle.loads(recv_data)
			global_map.update(local_map)

			total_to_be_read -= 1

			index_lists = dist_map[socket]
			copy_index_lists = copy.copy(index_lists)
			for il in index_lists:
				if il[0] == recv_start_index:
					copy_index_lists.remove(il)
			dist_map[socket] = copy_index_lists
	return []
开发者ID:aashray,项目名称:dist_crawl,代码行数:60,代码来源:main_handler.py

示例13: download_files

def download_files(socket, working_directory):
    send_en = False
# Firstly, sending requests for downloading and notify servers  
    send_messages(socket, 4)
    if socket.recv(1024) == "What's file name you want":
        file_name = raw_input("Please enter the name of file you want:")
	socket.send(file_name)
# if the server that the requested files exist, get the location of file
	respond = socket.recv(1024)
	if respond == "The requested file exists":
	    location = socket.recv(1024)
	    print "The file is located at " + location
	    send_en = True
	elif respond != "The requested file exists":
	    print "From Server - Error:The requested file doesn't exist"
# If send_en flag is true, begin transmitting files
    if send_en:
        socket.send("Please send file")
	file_name = working_directory + "/" + file_name
	f = open(file_name, "wb")
	content = socket.recv(1024)
#	print content
	while (content):
	    f.write(content)
            content = socket.recv(1024)
            if content == "###":
                break;
开发者ID:FighterCZY,项目名称:Cloud-Computing,代码行数:27,代码来源:client_side.py

示例14: recv

 def recv(socket, largo):
     buff = bytes()
     for i in range(1024, largo, 1024):
         buff += socket.recv(1024)
     falta = largo - len(buff)
     buff += socket.recv(falta)
     return buff
开发者ID:Yackpott,项目名称:public,代码行数:7,代码来源:cliente.py

示例15: __get_next_data

    def __get_next_data(self, socket):
        data = None
        try:
            data_len_bytes = socket.recv(4)
            recv_len = len(data_len_bytes)
            while recv_len < 4:
                left_len = 4 - recv_len
                data_len_bytes += socket.recv(left_len)
                recv_len = len(data_len_bytes)

            data_len = int.from_bytes(data_len_bytes, byteorder='little')
            data = socket.recv(data_len)
            recv_len = len(data)
            while recv_len < data_len:
                left_len = data_len - recv_len
                data += socket.recv(left_len)
                recv_len = len(data)
            #print(data)
            recv_data_str = data[8:-1].decode('utf-8', 'ignore')
            return recv_data_str
        except os.error as e:
            print(e)
        except UnicodeDecodeError as e:
            print(data)
            print(e)
开发者ID:xiaowei0828,项目名称:dota2_data_analyse,代码行数:25,代码来源:douyu_danmu.py


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