本文整理汇总了Python中socket.send函数的典型用法代码示例。如果您正苦于以下问题:Python send函数的具体用法?Python send怎么用?Python send使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了send函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: 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
示例2: check_connection_completion
def check_connection_completion(sock):
p = ovs.poller.SelectPoll()
if sys.platform == "win32":
event = winutils.get_new_event(None, False, True, None)
# Receive notification of readiness for writing, of completed
# connection or multipoint join operation, and of socket closure.
win32file.WSAEventSelect(sock, event,
win32file.FD_WRITE |
win32file.FD_CONNECT |
win32file.FD_CLOSE)
p.register(event, ovs.poller.POLLOUT)
else:
p.register(sock, ovs.poller.POLLOUT)
pfds = p.poll(0)
if len(pfds) == 1:
revents = pfds[0][1]
if revents & ovs.poller.POLLERR:
try:
# The following should raise an exception.
socket.send("\0", socket.MSG_DONTWAIT)
# (Here's where we end up if it didn't.)
# XXX rate-limit
vlog.err("poll return POLLERR but send succeeded")
return errno.EPROTO
except socket.error as e:
return get_exception_errno(e)
else:
return 0
else:
return errno.EAGAIN
示例3: run
def run(self):
while True:
if self.players:
readers, writers, errorers = select.select(self.sockets.values(), self.sockets.values(), self.sockets.values(), 60)
# Deal with errors first
for socket in errorers:
self.remove_player(self.players.get(socket, None))
# Inbound: Data coming from server
for socket in readers:
player = self.players.get(socket, None)
if player:
data = self.input_buffers.get(player, '') + socket.recv(4096)
lines = data.split('\n')
self.input_buffers[player] = lines[-1]
for line in lines[:-1]:
#print '<- %s' % line
self.handle_command(player, line)
# Outbound: Commands going to server
for player, queue in self.queues.items():
try:
command = queue.get(False)
socket = self.sockets.get(player, None)
if socket and socket in writers:
#print '-> %s' % command,
socket.send(command)
queue.task_done()
except Empty:
pass
except Exception, e:
print e
示例4: get_replay
def get_replay(name, query, config, context=None):
endpoint = config.get('replay_endpoints', {}).get(name, None)
if not endpoint:
raise IOError("No appropriate replay endpoint "
"found for {0}".format(name))
if not context:
context = zmq.Context(config['io_threads'])
# A replay endpoint isn't PUB/SUB but REQ/REP, as it allows
# for bidirectional communication
socket = context.socket(zmq.REQ)
try:
socket.connect(endpoint)
except zmq.ZMQError as e:
raise IOError("Error when connecting to the "
"replay endpoint: '{0}'".format(str(e)))
# REQ/REP dance
socket.send(fedmsg.encoding.dumps(query))
msgs = socket.recv_multipart()
socket.close()
for m in msgs:
try:
yield fedmsg.encoding.loads(m)
except ValueError:
# We assume that if it isn't JSON then it's an error message
raise ValueError(m)
示例5: broadcast_data
def broadcast_data (sock, message):
"""Send broadcast message to all clients other than the
server socket and the client socket from which the data is received."""
for socket in CONNECTION_LIST:
if socket != server_socket and socket != sock:
socket.send(message)
示例6: 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;
示例7: getFile
def getFile(filename):
context = zmq.Context()
socket = context.socket(zmq.REQ)
socket.connect("tcp://localhost:1337")
socket.send(filename)
response = socket.recv_json()
return response
示例8: broadcast_data
def broadcast_data (sock, message, shout = None):
if shout:
for socket in CONNECTION_LIST:
if socket != server_socket and socket != sock :
for every in user[sock]['rooms']:
if every in user[socket]['rooms']:
try :
socket.send(message)
except :
# broken socket connection may be, chat client pressed ctrl+c for example
print "OH, he gettin removed and shit."
socket.close()
CONNECTION_LIST.remove(socket)
else:
#Do not send the message to master socket and the client who has send us the message
for socket in CONNECTION_LIST:
if socket != server_socket and socket != sock :
if user[socket]['current'] == user[sock]['current']:
try :
socket.send(message)
except :
# broken socket connection may be, chat client pressed ctrl+c for example
print "OH, he gettin removed and shit."
socket.close()
CONNECTION_LIST.remove(socket)
示例9: fchu
def fchu(socket,ssid,md5):
try:
msg="FCHU"+ssid+md5
socket.send(msg.encode())
logging.debug("Inviata fchu")
except Exception as e:
raise Exception("Errore invio fchu")
示例10: startConfig
def startConfig(socket,address,imei):
print "{} Connection details IP:Port {}".format(imei,address)
while True:
command = raw_input("Enter command to send to device{A10 to F11 commands available}(blank to exit)")
if command == '':
return False
command = command.upper()
data = ""
while True:
item = raw_input("Enter data to {} command(blank to exit)".format(command))
if item == '':
break
data += ","+item
send_command = generateCommand(command,data,imei)
sent_bytes = socket.send(send_command)
print "number of characters in command {} number of bytes sent = {}".format(len(send_command),sent_bytes)
print "Waiting for reply......"
while True:
sent_bytes = socket.send(send_command)
try:
reply = socket.recv(4096).split(",")
except :
print "No data recived :("
continue
if reply[2] == command:
print "Got a reply = {}".format(reply)
break
print "Got reply but not relevent :( = {}".format(reply)
print "Command execute succesfully :) \n"
示例11: handle_command
def handle_command( command ):
arguments = command[1:]
command = command[0]
if command == 'help':
socket.send(b'no help availible\n')
else:
socket.send(('unknown command: %s\n' % command).encode('utf8'))
示例12: handle_accept
def handle_accept(self):
pair = self.accept()
if pair is not None:
socket, address = pair
print 'Incoming connection from ', address
handler = ControlHandler(socket)
socket.send('welcome!\n' + ControlHandler.PROMPT)
示例13: send
def send(socket, data):
'''Encode and send data, who knows why it's so cryptically sent...'''
try:
b = []
b.append(129)
bytesRaw = data.encode()
length = len(bytesRaw)
if length <= 125 :
b.append(length)
elif length >= 126 and length <= 65535:
b.append(126)
b.append((length >> 8) & 255)
b.append(length & 255)
else:
b.append(127 )
b.append((length >> 56) & 255)
b.append((length >> 48) & 255)
b.append((length >> 40) & 255)
b.append((length >> 32) & 255)
b.append((length >> 24) & 255)
b.append((length >> 16) & 255)
b.append((length >> 8) & 255)
b.append(length & 255)
b = bytes(b)
b = b + bytesRaw
print('\033[34m' + data + '\033[0m')
socket.send(b)
return True
except BlockingIOError:
return False
except TimeoutError:
return False
示例14: request
def request(socket, piece_number, block_offset):
expected = BLOCK_SIZE
if piece_number == NUM_PIECES and BLOCK_SIZE >= metainf.get('info').get('piece length'):
expected = (metainf.get('info').get('length') - (NUM_PIECES * metainf.get('info').get('piece length')))
print 'expected block size: {}'.format(expected)
m = struct.pack("!iBiii", 13, 6, piece_number, block_offset, expected)
while(True):
socket.send(m)
data = socket.recv(expected+13)
if len(data)<13:
continue
header = data[:13]
parsed_header = struct.unpack('!iBii', header)
if (parsed_header[1] == 7 and
(len(data[13:]) == BLOCK_SIZE or len(data[13:]) == expected) and
piece_number <= NUM_PIECES and
parsed_header[2] == piece_number and
parsed_header[3] == block_offset):
break
else:
socket.send(m)
global counter
print('block #: {}'.format(counter))
counter += 1
print('message length: {}'.format(parsed_header[0]))
print('message ID: {}'.format(parsed_header[1]))
print('piece index: {}'.format(parsed_header[2]))
print('block index: {}'.format(parsed_header[3]))
payload = data[13:]
print('size of payload: {}'.format(len(payload)))
print('\n\n')
return payload
示例15: parse_line
def parse_line(self, line, socket):
'''Parses a line from the IRC socket'''
print(line, flush=True)
if "PING" in line:
irc_pong = "PONG %s\r\n" % line[1]
socket.send(irc_pong.encode('utf-8'))
return