我正在创建一个套接字客户端,并尝试获取一些数据。为此,我需要通过套接字连接到Web服务器,并且服务器实际上创建了另一个套接字,该套接字监听并等待数据,然后将其发送回客户端。
以下代码存在的问题是我的套接字客户端不等待服务器接收的数据,而只接受空数据。
如何使用Python套接字等待服务器中的非空数据?
我的代码:
import sys
import json
import socketIO_client
import time
host = 'https://SOME_URL'
socketIO = socketIO_client.SocketIO(host, params={"email" : "edmund@gmail.com"})
def on_connect(*args):
print "socket.io connected"
def on_disconnect(*args):
print "socketIO diconnected"
socketIO.on('connect', on_connect)
socketIO.on('disconnect', on_disconnect)
def on_response_state(*args):
print args # Prints ()
socketIO.emit('receive_state',on_response_state)
socketIO.wait_for_callbacks(seconds=3)
答案 0 :(得分:2)
以下是使用socket
的示例。使用s.accept()
,客户端将等待直到客户端接受连接,然后再开始while
循环以接收数据。这应该可以解决您的问题。
def receiver():
PORT = 123
CHUNK_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('0.0.0.0', PORT))
s.listen(1)
conn,address=s.accept() # accept an incoming connection using accept() method which will block until a new client connects
while True:
datachunk = conn.recv(CHUNK_SIZE) # reads data chunk from the socket in batches using method recv() until it returns an empty string
if not datachunk:
break # no more data coming in, so break out of the while loop
data.append(datachunk) # add chunk to your already collected data
conn.close()
print(data)
return
receiver()
答案 1 :(得分:1)
将recv套接字放入while线程中。
像这样:
def rec(self):
while 1:
sleep 0.01
rdata = self.clientsocket.recv(self.buffsize)
print("rec from server: ", rdata.decode('utf8'),'\n','press enter to continue')
....
t2 = threading.Thread(target=y.rec, name="rec")
t2.start()
答案 2 :(得分:0)
由于您正在使用SocketIO
库来包含参数(使用requests实现)并希望发出消息,因此可以通过不指定等待时间来无限期地等待响应。 / p>
with SocketIO(host, params={"email" : "edmund@gmail.com"}) as socketIO:
def on_response_state(*args):
print args # Prints ()
socketIO.emit('receive_state', on_response_state)
socketIO.wait()