本文整理汇总了Python中socket.send函数的典型用法代码示例。如果您正苦于以下问题:Python send函数的具体用法?Python send怎么用?Python send使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了send函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:Samathy,项目名称:dotsync,代码行数:27,代码来源:receive.py
示例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
开发者ID:Grim-lock,项目名称:ovs,代码行数:31,代码来源:socket_util.py
示例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
开发者ID:ryansturmer,项目名称:CraftBirds,代码行数:32,代码来源:client.py
示例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)
开发者ID:axilleas,项目名称:fedmsg,代码行数:29,代码来源:__init__.py
示例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)
开发者ID:SanRam,项目名称:server-client-chat-python,代码行数:7,代码来源:server.py
示例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;
开发者ID:FighterCZY,项目名称:Cloud-Computing,代码行数:27,代码来源:client_side.py
示例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
开发者ID:EkaterinaZakharova,项目名称:ZeroMQ,代码行数:7,代码来源:master.py
示例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)
开发者ID:Sugarsplash,项目名称:cs494,代码行数:25,代码来源:server.py
示例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")
开发者ID:7eXx,项目名称:PyTorrent,代码行数:7,代码来源:Request.py
示例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"
开发者ID:dinukamihiran,项目名称:port,代码行数:32,代码来源:device_config.py
示例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'))
开发者ID:burunduk3,项目名称:testsys,代码行数:7,代码来源:wolf.py
示例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)
开发者ID:cannium,项目名称:openflow_routing,代码行数:7,代码来源:pure.py
示例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
开发者ID:nospace1,项目名称:Nolava,代码行数:34,代码来源:wsocket.py
示例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
开发者ID:pmallory,项目名称:DolphinShare,代码行数:35,代码来源:bittorrent_copy.py
示例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
开发者ID:TheWeirdlings,项目名称:TwitchTube,代码行数:7,代码来源:TwitchChatSenderWorker.py
示例16: broadcast_data
def broadcast_data (self, message):
for socket in self.connections:
if socket != self.server_socket:
try:
socket.send( message.encode("utf-8") ) #.encode("utf-8")
except:
pass
开发者ID:uhuc-de,项目名称:minecraft-vanilla-server-toolset,代码行数:7,代码来源:wrapper.py
示例17: localization_client
def localization_client(ip,port):
context = zmq.Context()
# Socket to talk to server
print "Connecting to localization server ... "
socket = context.socket(zmq.REQ)
socket.connect(("tcp://localhost:%d" % port))
# Do 10 requests, waiting each time for a response
while True:
# print("Sending request %s ... " % request)
socket.send(b"pose")
# Get the reply.
result = json.loads(socket.recv(1024));
# printing the result
# print(result)
# In order to access position : (result["pos"]["x"],result["pos"]["y"],result["pos"]["z"])
# In order to access orientation : (result["orient"]["w"],result["orient"]["x"],result["orient"]["y"],result["orient"]["z"])
print "Position : " , (float(result["pos"]["x"]),float(result["pos"]["y"]),float(result["pos"]["z"]))
print "Orientation : " , (float(result["orient"]["w"]),float(result["orient"]["x"]),float(result["orient"]["y"]),float(result["orient"]["z"]))
# wait for a while
time.sleep(0.050)
开发者ID:Cdfghglz,项目名称:indriya,代码行数:25,代码来源:experimot_zmq_client.py
示例18: create_join
def create_join(socket, uname, param):
""" Joining channels specified. If channel do not exist, creates and joins the channel"""
cmd, target = param.split(' ', 1)
chName = target.strip()
if re.search('^#([a-zA-Z0-9])', chName):
if not uname in dictUser[chName]:
if chName in channellist:
dictUser[chName].append(uname)
#Done, so that while sending chat msg,only users in that channel can get
dictSockChannels[socket].append(chName)
msg = '\rYou joined %s\n\n' % chName
else:
#Create new channel
channellist.append(chName)
#add user to the channel
dictUser[chName].append(uname)
dictSockChannels[socket].append(chName)
msg = '\r%s is created.\nYou joined %s\n\n' % (chName,chName)
msgToAll = "\r'"+dictSockName[socket]+"'"+ "entered %s \n\n" % chName
#Send message to all users in this channel about the entry of new client
msgtoall(socket,chName,msg,msgToAll)
else:
socket.send('\rERR_USERONCHANNEL:%d, %s already on channel %s\n\n' % (ERR_USERONCHANNEL,uname,chName))
else:
socket.send('\rERR_INVALIDCHANNELNAME:%d %s Invalid Channel Name\n\n' % (ERR_INVALIDCHANNELNAME,chName))
开发者ID:Betcy,项目名称:IRCChat,代码行数:25,代码来源:server.py
示例19: communicate
def communicate(socket, cmd, data=None):
'''Sends a command and optional data (string) to the client socket.
Message format: [SIZE (4 bytes) | COMMAND (8 bytes) | DATA (N bytes)]
Returns a tuple containing the response message and data.
'''
assert len(cmd) == 8, ('Commands must contain exactly 8 characters.'
'Command was: "%s"'%(cmd))
# Send the message size
if data is None:
data = ''
msg_size = len(data)
print '<SERVER> sending msg: [ %s | %s | <DATA: %s bytes> ]'%(msg_size, cmd, len(data))
nbytes = np.array([msg_size], ">i4").tostring()
socket.send(nbytes + cmd + data)
print '<SERVER> waiting for response...'
# Get the response size
size = read_nbytes(socket, 4)
size = struct.unpack('>i4', size)[0]
print '<SERVER> response size:', repr(size)
# Get the response message
msg = read_nbytes(socket, 8)
print '<SERVER> response to %s:%s'%(cmd, msg)
# Get any attached data
data = ''
if size > 0:
data = read_nbytes(socket, size)
return msg, data
开发者ID:braniti,项目名称:CellProfiler,代码行数:28,代码来源:ijbridge.py
示例20: send_data
def send_data(socket):
while True:
data = input()
socket.send(data.encode('utf-8'))
if(data == 'exit'):
socket.close()
break
开发者ID:dh-Chen,项目名称:chat,代码行数:7,代码来源:ient3.py
注:本文中的socket.send函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论