本文整理匯總了Python中socket.recv方法的典型用法代碼示例。如果您正苦於以下問題:Python socket.recv方法的具體用法?Python socket.recv怎麽用?Python socket.recv使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類socket
的用法示例。
在下文中一共展示了socket.recv方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _getchunk
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import recv [as 別名]
def _getchunk(self,socket):
#Struct of header - first 12 bytes
# end xmlsize type ? id chunk# *10 total chunks \0
# -- -------- ----- ------ ---- --------- ------------- --
# 00 00 00 00 F1 X 0 00 00 00 00 00 00
#FIXME: XMLsize print is incorrect
data = socket.recv(1500)
chunk = {}
chunk["end"] = struct.unpack('B',data[:1])[0]
chunk["size"] = struct.unpack('>HB',data[1:4])[0]
chunk["filetype"] = struct.unpack('B',data[4:5])[0]
chunk["fileid"] = struct.unpack('>H',data[5:7])[0]&0x0fff
chunk["chunk_number"] = struct.unpack('>H',data[8:10])[0]/0x10
chunk["chunk_total"] = struct.unpack('B',data[10:11])[0]
chunk["data"] = data[12:]
self.logger.debug("Chunk "+str(chunk["chunk_number"])+"/"+str(chunk["chunk_total"])+" ---- e:"+str(chunk["end"])+" s:"+ str(chunk["size"])+" f:"+str(chunk["fileid"]))
return chunk
示例2: _read_from_socket
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import recv [as 別名]
def _read_from_socket(self):
"""
Read socket.recv to the readed_jsons queue
Returns
-------
"""
data = ""
try:
data = self.__socket.recv(SOCKET_BUFFER_SIZE)
except socket.timeout:
self.state["Errors"] = True
raise socket.timeout("Error! Socket did not get info, when expected")
if not data:
s = "Empty"
else:
s = data.decode('utf-8')
print("\n === Read from socket === \n%s\n" % s)
self._load_to_queue(s)
示例3: testRecv
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import recv [as 別名]
def testRecv(self):
# Testing non-blocking recv
conn, addr = self.serv.accept()
self.addCleanup(conn.close)
conn.setblocking(0)
# the server didn't send data yet: non-blocking recv() fails
with self.assertRaises(socket.error):
msg = conn.recv(len(MSG))
self.event.set()
read, write, err = select.select([conn], [], [], MAIN_TIMEOUT)
if conn not in read:
self.fail("Error during select call to non-blocking socket.")
# the server sent data yet: non-blocking recv() doesn't block
msg = conn.recv(len(MSG))
self.assertEqual(msg, MSG)
示例4: _recvall
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import recv [as 別名]
def _recvall(self):
"""
Receive btyes from socket.recv().
return s type: bytes
"""
s = b""
while self._data_available():
try:
data = self._socket.recv(1024)
except socket.error as e:
raise MonitorSocketError("Could not receive data from monitor",
e)
if not data:
self._server_closed = True
break
s += data
return s
示例5: _raise_connection_failure
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import recv [as 別名]
def _raise_connection_failure(self, error):
# Catch *all* exceptions from socket methods and close the socket. In
# regular Python, socket operations only raise socket.error, even if
# the underlying cause was a Ctrl-C: a signal raised during socket.recv
# is expressed as an EINTR error from poll. See internal_select_ex() in
# socketmodule.c. All error codes from poll become socket.error at
# first. Eventually in PyEval_EvalFrameEx the interpreter checks for
# signals and throws KeyboardInterrupt into the current frame on the
# main thread.
#
# But in Gevent and Eventlet, the polling mechanism (epoll, kqueue,
# ...) is called in Python code, which experiences the signal as a
# KeyboardInterrupt from the start, rather than as an initial
# socket.error, so we catch that, close the socket, and reraise it.
self.close()
if isinstance(error, socket.error):
_raise_connection_failure(self.address, error)
else:
raise error
示例6: __waitfor_client_register
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import recv [as 別名]
def __waitfor_client_register(self):
self.request.settimeout(5)
try:
devicetypetmp=self.request.recv(20)
self._client_devicetype = devicetypetmp.decode('utf-8')
_ClientHandler.log_info("Client-ID:{0}; register(); got devicetype:{1}".format(self._myownID,self._client_devicetype))
#send client-ID to client
sendtemp=str(self._myownID)
self.request.sendall(sendtemp.encode("utf-8"))
except socket.timeout:
_ClientHandler.log_critical("Client-ID:{0}; Timeout occured, no devicetype was send".format(self._myownID))
raise
except socket.error as e:
# Something else happened, handle error, exit, etc.
_ClientHandler.log_critical("Client-ID:{0}; error '{1}' on socket.recv or socket.send".format(self._myownID, e))
raise
except Exception as e:
_ClientHandler.log_critical("Client-ID:{0}; unkown error '{1}'".format(self._myownID,e))
raise
finally:
self.request.settimeout(None)
示例7: read
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import recv [as 別名]
def read(self, size=1):
"""Read size bytes from the connected socket. It will block
until the requested number of bytes are read.
"""
if self._socket==None:
raise ("Client-ID:{0}; cht_socket_client.read(); error:socket not initialised".format(self._clientID))
read=bytearray()
while len(read) < size:
try:
buffer=self._socket.recv(size)
except:
self._socket.close()
self.log_critical("Client-ID:{0}; cht_socket_client.read(); error on socket.recv".format(self._clientID))
raise
if not buffer:
self._socket.close()
self.log_critical("Client-ID:{0}; cht_socket_client.read(); peer closed socket".format(self._clientID))
raise
else:
read.extend(buffer)
return bytes(read)
示例8: testRecv
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import recv [as 別名]
def testRecv(self):
# Testing non-blocking recv
conn, addr = self.serv.accept()
conn.setblocking(0)
try:
msg = conn.recv(len(MSG))
except socket.error:
pass
else:
self.fail("Error trying to do non-blocking recv.")
read, write, err = select.select([conn], [], [])
if conn in read:
msg = conn.recv(len(MSG))
conn.close()
self.assertEqual(msg, MSG)
else:
self.fail("Error during select call to non-blocking socket.")
示例9: test_tunnel
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import recv [as 別名]
def test_tunnel(self):
hook = SSHHook(ssh_conn_id='ssh_default')
import subprocess
import socket
subprocess_kwargs = dict(
args=["python", "-c", HELLO_SERVER_CMD],
stdout=subprocess.PIPE,
)
with subprocess.Popen(**subprocess_kwargs) as server_handle, hook.create_tunnel(2135, 2134):
server_output = server_handle.stdout.read(5)
self.assertEqual(b"ready", server_output)
socket = socket.socket()
socket.connect(("localhost", 2135))
response = socket.recv(5)
self.assertEqual(response, b"hello")
socket.close()
server_handle.communicate()
self.assertEqual(server_handle.returncode, 0)
示例10: download
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import recv [as 別名]
def download(s):
filename = s.recv(1024)
print(filename)
if(os.path.isfile(filename)):
with open(filename, 'rb') as f:
l = f.read(1024)
l = 'True+/-' + l
while(l):
s.send(l)
l = f.read(1024)
print('sent')
s.shutdown(s.SHUT_WR)
else:
s.send('False')
示例11: receive
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import recv [as 別名]
def receive(self, size, timeout=30):
"""
Receive a message.
:param size: Number of bytes to receive.
:type size: ``int``
:param timeout: Timeout in seconds.
:type timeout: ``int``
:return: message received
:rtype: ``bytes``
"""
if timeout != self._timeout:
self._timeout = timeout
self._client.settimeout(timeout)
try:
msg = self._client.recv(size)
except Exception:
if timeout == 0:
raise socket.timeout
raise
return msg
示例12: test_connection_closed
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import recv [as 別名]
def test_connection_closed(self, rpc):
rpc.handshake()
# Mock socket.recv returning an empty string, as it does when the
# connection has been closed.
class MockSocket:
def sendall(self, content):
pass
def recv(self, size):
return ""
def close(self):
pass
rpc._socket = MockSocket()
with pytest.raises(connection.SerfConnectionError):
rpc.handshake()
示例13: _receive
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import recv [as 別名]
def _receive(self, count):
"""Reads data from the livestatus plugin."""
results = []
while count > 0:
try:
data = self._sock.recv(count)
except socket.error as err:
raise NagiosResponseError(err)
if len(data) == 0:
msg = 'Failed to read data from nagios server.'
raise NagiosResponseError(msg)
count -= len(data)
# socket.recv() returns str in Python 2 and bytes in Python 3
if sys.version_info[0] >= 3:
data = data.decode()
results.append(data)
return ''.join(results)
示例14: initDiffieHellman
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import recv [as 別名]
def initDiffieHellman(self):
if self.request.recv(1024).decode() != "connected":
print("Error while connecting")
publicSecret = self.__dh.calcPublicSecret()
step1 = "{"
step1 += "\"dh-keyexchange\":"
step1 += "{"
step1 += "\"step\": {},".format(1)
step1 += "\"base\": {},".format(self.__dh.base)
step1 += "\"prime\": {},".format(self.__dh.sharedPrime)
step1 += "\"publicSecret\": {}".format(publicSecret)
step1 += "}}"
self.request.send(step1.encode())
step2 = self.request.recv(1024)
if self.__debugflag:
print(step2)
jsonData = json.loads(step2.decode())
jsonData = jsonData["dh-keyexchange"]
publicSecret = int(jsonData["publicSecret"])
self.__dh.calcSharedSecret(publicSecret)
示例15: receive
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import recv [as 別名]
def receive(self, timeout=30):
"""
Receive data.
:param timeout: time-out, default 30 sec
:type timeout: float
"""
if not self.socket:
raise RemoteEndpointNotConnected()
ready = select.select([self.socket], [], [], timeout)
if ready[0]:
try:
data = self.socket.recv(self.receive_buffer_size)
# TODO: rework logging to have LogRecord with extra=direction
# TODO: separate data sent/received from other log records ?
self._debug('< {}'.format(data))
except socket.error as serr:
if (serr.errno == 10054) or (serr.errno == 10053):
self._close_ignoring_exceptions()
raise RemoteEndpointDisconnected(serr.errno)
else:
raise serr
if not data:
self._close_ignoring_exceptions()
raise RemoteEndpointDisconnected()
return data
else:
# don't want to show class name - just tcp address
# want same output from any implementation of TCP-connection
info = "Timeout (> %.3f sec) on {}".format(timeout, self)
raise ConnectionTimeout(info)